Set specific line of multiline TextBox in c#

2019-09-15 08:02发布

问题:

Hello I am new to C Sharp & Windows Forms. I am unable to set the specific string of a multiline TextBox. I have tried below things so far.

textBox1.Lines[1] = "welcome to stackOverflow";

The above code does not give a compile time error but when I saw the result using Debug mode it was not expected.

Then i was also reading this MSDN article but in this there is a new collection created by using stream[] constructor but still the same problem arises.

回答1:

It should give compiler error because you are trying to assign a string to char here:

textBox1.Text[1] = "welcome to stackOverflow";

Text property is of type string, when you use indexer on a string it gives you the char at that position. And also string is immutable so you can't really change a character at specific position without creating a new string.

You should set the Text directly like this:

textBox1.Text = "welcome to stackOverflow";

Or if you have more than one line in an array of string you should set the Lines property:

var lines = new [] { "foo", "bar" };
textBox1.Lines = lines;


回答2:

Any value that you set directly to textBox1.Lines will be effected to textBox1.

There is a solution to resolve your problem. I think it's best way. You have to clone the current value of your textbox. Then you set new value on it. Finally, you set back to textbox.

var curValue = (string[])textBox1.Lines.Clone();
curValue[1] = "welcome to stackOverflow";

//Set back to textBox1
textBox1.Lines = curValue;