开发者

C#: how to insert string containing new lines into TextBox?

开发者 https://www.devze.com 2023-01-09 23:14 出处:网络
How do you insert a string containing new lines int开发者_如何学Goo a TextBox? When I do this using \\n as the new line character, it doesn\'t work.You have to set the multiline property of the textb

How do you insert a string containing new lines int开发者_如何学Goo a TextBox?

When I do this using \n as the new line character, it doesn't work.


You have to set the multiline property of the textbox to true and you can use

Environment.NewLine

as the new line char.

You can also use \r\n instead of Environment.NewLine

TextBox1.Text = "First line\r\nSecond line"


As the other answers say you have to set .Multiline = true, but I don't think you then have to use the Lines property. If you already have the text as one string you can then assign it to the Text property as normal. If your string contains '\n' as separators you can do a replace to the current system's newline:

textBox1.Text = myString.Replace("\n", Environment.NewLine);


The first method is:

textbox1.Text = "First " + System.Environment.NewLine + " Second";

The second method is:

textbox1.Text = "First \r\n Second";


First, set the TextBox.Multiline property to true. Then you can assign the TextBox.Lines property to an array of strings.

textbox.Lines = s.Split('\n');


Firstly you need to set the TextBox.Multiline property to true.

Then you need to get the text into the text box, you have two options for this.

  • Set the lines as an array of strings:

    textbox.Lines = s.Split('\n');

  • Otherwise you need to use the windows line end (“\r\n”) rather than the unix/c line end (“n”) when setting the text. This can be done using Environment.NewLine if you wish to make the code a bit clearer.

    textBox1.Text = myString.Replace("\n", Environment.NewLine);

If you wish your code to cope with both types of line ends, then you can strips out the “\r” before doing one of the above. Line terminators in stings are still a lot larger pain then they should be!

0

精彩评论

暂无评论...
验证码 换一张
取 消