问题
I am unable to Change the specific string of a multiline TextBox.
suppose first line of multiline textbox is "Hello"
& second line is "Bye"
.But when i trying to change the value of second line like below.
textBox1.Lines[1] = "Good bye";
When I saw the result using Debug mode it was not "Good bye".
I also read this MSDN article & this stackoverflow question but can't get the desired answer.
回答1:
As MSDN states (the link you provided):
By default, the collection of lines is a read-only copy of the lines in the TextBox. To get a writable collection of lines, use code similar to the following: textBox1.Lines = new string[] { "abcd" };
So, you have to "take" Lines
collection, change it, and then return to TextBox
. That can be achieved like this:
var lines = TextBox1.Lines;
lines[1] = "GoodBye";
TextBox1.Lines = lines;
Alternatively, you can replace text, like Wolle suggested
回答2:
First you need assign textBox1.Lines
array in variable
string[] lines = textBox1.Lines;
Change Array Value
lines[1] = "Good bye";
Reassign array to text box
textBox1.Lines=lines;
According to MSDN
By default, the collection of lines is a read-only copy of the lines in the TextBox. To get a writable collection of lines need to assign new string array
回答3:
You could try to replace the text of second line like this:
var lines = textBox.Text.Split(new[] { '\r', '\n' }).Where(x => x.Length > 0);
textBox.Text = textBox.Text.Replace(lines.ElementAt(1), "Good bye");
回答4:
Working with TextBox
lines via Lines
property are extremely ineffective. Working with lines via Text
property is a little better, but ineffective too.
Here the snippet, that allows you to replace one line inside TextBox
without rewriting entire content:
public static bool ReplaceLine(TextBox box, int lineNumber, string text)
{
int first = box.GetFirstCharIndexFromLine(lineNumber);
if (first < 0)
return false;
int last = box.GetFirstCharIndexFromLine(lineNumber + 1);
box.Select(first,
last < 0 ? int.MaxValue : last - first - Environment.NewLine.Length);
box.SelectedText = text;
return true;
}
来源:https://stackoverflow.com/questions/44112453/change-particular-line-of-multiline-textbox-in-c-sharp