Reputation: 83
I'm a newbie in C# programming, and I don't understand how character escaping works. I tried many of them, but only '\t' works like it should. An example for my code:
textBox1.Text = "asd";
textBox1.Text = textBox1.Text + '\n';
textBox1.Text = textBox1.Text + "asd";
MultiLine is enabled, but my output is simply "asdasd" without breaking the line. I hope some of you knows what the answer is.
Upvotes: 1
Views: 152
Reputation: 1503799
You need "\r\n"
for a line break in Windows controls, because that's the normal line break combination for Windows. (Line breaks are the bane of programmers everywhere. Different operating systems have different character sequences that they use as their "typical" line breaks.)
"\r\n"
is two characters: \r
for carriage return (U+000D) and \n
for line feed (U+000A). You don't need to do it in three statements though:
textBox1.Text = "First line\r\nSecond line";
Now, I've deliberately gone with \r\n
there instead of Environment.NewLine
, on the grounds that if you're working with System.Windows.Forms
, those will be Windows-oriented controls. It's unclear to me what an implementation of Windows Forms will do on Mac or Linux, where the normal line break is different. (My guess is that a pragmatic implementation will break on any of \r
, \n
or \r\n
, just like TextReader
does, for simplicity.)
Sometimes - such as if you're writing a text file for consumption on the same machine - it's good to use Environment.NewLine
.
Sometimes - such as when you're implementing a network protocol such as HTTP which mandates a specific line break format - it's good to be explicit about it.
Sometimes - such as in this case - it's just not clear. However, it's always worth thinking about.
For a complete list of escape sequences in C#, you can either look at the C# language specification (always fun!) or look at my Strings article which contains that information and more.
Upvotes: 9
Reputation: 2272
The most legible way to insert a newline in C# is:
textBox1.Text = "asd";
textBox1.Text = textBox1.Text + Environment.NewLine;
textBox1.Text = textBox1.Text + "asd";
This code snippet would set textBox1
text to "asd
", then add a newline to it, then on the second line, it would add "asd
" again.
The special characters you are confused about are artifacts from when computers used teletype printers for all of their output. Teletype printers predated digital displays by several years.
Combined, this resulted in the print head being positioned at the start of the next row, ready for output onto clean paper.
Further information can be sought out on the internet with ease, including places such as Wikipedia's NewLine article
Upvotes: 5