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

ぃ、小莉子 提交于 2019-12-22 02:01:35

问题


How do you insert a string containing new lines into a TextBox?

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


回答1:


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"



回答2:


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);



回答3:


The first method is:

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

The second method is:

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



回答4:


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');



回答5:


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!



来源:https://stackoverflow.com/questions/3403731/c-how-to-insert-string-containing-new-lines-into-textbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!