Nathan Campos
Nathan Campos

Reputation: 29507

How To Use \n In a TextBox

I'm developing a program that I'm using a string(generatedCode) that contains some \n to enter a new-line at the textBox that I'm using it(textBox1.Text = generatedCode), but when I'm running the program, instead of breaking that line I'm seeing a square.

Remember that I've set the Multiline value of the textBox to True.

Upvotes: 26

Views: 70241

Answers (5)

Mitrakov Artem
Mitrakov Artem

Reputation: 1533

In newer .NET versions you can use:

textBox1.Text = data.ReplaceLineEndings();

Upvotes: 0

dancer42
dancer42

Reputation: 189

since using \n is easier on the eyes (especailly when formatting), and also sometimes you don't control how the source string is constructed - I find best practice is to use:
TextBox1.Text = str.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);

Upvotes: 10

MakoCSH
MakoCSH

Reputation: 71

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

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

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1503040

Replace \n with \r\n - that's how Windows controls represent newlines (but see note at bottom):

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

or

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

Note: As discussed in comments, you may want to use Environment.NewLine. It's unclear though - it's not well-defined what line separator Windows Forms controls should use when they're not running on Windows. Should they use the platform default, or the Windows one (as it's a port of a Windows GUI control)? One of the examples in MSDN does use Environment.NewLine, but I've seen horribly wrong examples in MSDN before now, and the documentation just doesn't state which is should be.

In an ideal world, we'd just have one line separator - and even in a second best world, every situation would clearly define which line separator it was expecting...

Upvotes: 56

Bob
Bob

Reputation: 99814

Usually \r\n gets me a newline in a textbox. Try replacing your \n with \r\n just be careful you don't have a mix of \r\n and \n

Upvotes: 6

Related Questions