views:

62

answers:

4

c#: 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.

+3  A: 

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"
Jonathan
+1  A: 

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');
Felix Ungman
+2  A: 

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);
Evgeny
A: 

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!

Ian Ringrose