How to use \ n in a text box

I am developing a program in which I use a line ( generatedCode ) that contains some \n to enter a new line in the text field that I use ( textBox1.Text = generatedCode ), but when I run the program, instead of breaking this line I see a square.

Remember that I set the Multiline textBox value to True .

+17
string c # newline
Nov 17 '09 at 19:59
source share
4 answers

Replace \ n with \ r \ n - the way Windows controls represent newlines (but see the note below):

 textBox1.Text = generatedCode.Replace("\n", "\r\n"); 

or

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

Note. As discussed in the comments, you can use Environment.NewLine . However, it is unclear - it is not determined which element of the Windows Forms line separator should use if it does not work on Windows. Should they use the default platform or a single Windows (like the Windows GUI management port)? One example on MSDN uses Environment.NewLine , but so far I have seen terribly incorrect examples on MSDN, and the documentation just doesn't say what should be.

In an ideal world, we will have only one line separator - and even in the second best world, each situation will clearly determine which line separator he expected ...

+40
Nov 17 '09 at 20:02
source share

Usually \r\n returns me a new line in the text box. Try replacing \n with \r\n , just be careful, you donโ€™t have a combination of \r\n and \n

+6
Nov 17 '09 at 20:02
source share

since using \ n is easier on the eyes (especially when formatting), and sometimes you donโ€™t control how the original line is created - I believe that the best practice is to use:
TextBox1.Text = str.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);

+6
Feb 15 2018-12-15T00:
source share

Add a carriage return (\ r) and it should work:

 TextBox1.Text = "First line\r\nSecond line"; 
+4
Nov 17 '09 at 20:04
source share



All Articles