Inserting text in a particular line of a textbox in .Net
I would like to insert text in a particular line, and replacing the text in the same line.
Eg
This is line 1
This is line 2
This is line 3
Now i would like to replace the text in line 2 to this is new line 2
is this p开发者_StackOverflowossible?
One option is to split the text on line breaks, change the second element of the resultant array, and then rejoin into a string and set the Text property. Something like
string[] array = textBox.Text.Split('\n');
array[position] = newText;
textBox.Text = string.Join('\n', array);
You could use the RegEx object to split the text.
Call the ReplaceLine() method like this:
private void btnReplaceLine_Click(object sender, RoutedEventArgs e)
{
string allLines = "This is line 1" + Environment.NewLine + "This is line 2" + Environment.NewLine + "This is line 3";
string newLines = ReplaceLine(allLines, 2, "This is new line 2");
}
The ReplaceLine() method implementation:
private string ReplaceLine(string allLines, int lineNumber, string newLine)
{
System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex(Environment.NewLine);
string newLines = "";
string[] lines = reg.Split(allLines);
int lineCnt = 0;
foreach (string oldLine in lines)
{
lineCnt++;
if (lineCnt == lineNumber)
{
newLines += newLine;
}
else
{
newLines += oldLine;
}
newLines += lineCnt == lines.Count() ? "" : Environment.NewLine;
}
return newLines;
}
精彩评论