C#: how to insert string containing new lines into

2019-04-18 02:51发布

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.

5条回答
Emotional °昔
2楼-- · 2019-04-18 03:15

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');
查看更多
Melony?
3楼-- · 2019-04-18 03:17

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!

查看更多
Lonely孤独者°
4楼-- · 2019-04-18 03:26

The first method is:

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

The second method is:

textbox1.Text = "First \r\n Second";
查看更多
Emotional °昔
5楼-- · 2019-04-18 03:29

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"
查看更多
一夜七次
6楼-- · 2019-04-18 03:33

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);
查看更多
登录 后发表回答