TextBox.AppendText
TextBox
provides the C# AppendText
method. This method appends lines of text. With it we have to deal with newlines and avoid extra line breaks.
If we append newlines on each line, there will be an extra blank line at the end of our multiline TextBox
. This can be avoided with some custom logic.
AppendText
exampleWe can append text to a TextBox
with the method AppendText
. But this call will not append a newline to the end—all the text will run together.
textBox1.AppendText
("text") two times, the text will be on the same line.private void Test() { for (int i = 0; i < 2; i++) { textBox1.AppendText("Some text"); } }Some textSome text
We can append lines by using Environment.NewLine
and then adding some conditional logic. Unlike AppendLine
, this does not add extra newlines.
string
value that represents a newline. It equals \r\n.public partial class Form1 : Form { private void AppendTextBoxLine(string myStr) { if (textBox1.Text.Length > 0) { textBox1.AppendText(Environment.NewLine); } textBox1.AppendText(myStr); } private void TestMethod() { for (int i = 0; i < 2; i++) { AppendTextBoxLine("Some text"); } } }Some text Some text
If we do not check the length of the Text in the TextBox
, we will have unwanted line breaks. But Sometimes we may prefer to always append newlines.
public partial class Browser : Form { private void Test() { // Will leave a blank line on the end. for (int i = 0; i < 2; i++) { textBox1.AppendText("Some text" + Environment.NewLine); } // Will leave a blank line on the start. for (int i = 0; i < 2; i++) { textBox1.AppendText(Environment.NewLine + "Some text"); } } }
These 2 tables demonstrate what the TextBox
contents will look like when there is a newline on the end always, and when there is a newline on the start.
TextBox
is appending the strings themselves.[Some text Some text ][Some text Some text]
We appended lines to a TextBox
with methods written in C#. These methods work well with events like TextChanged
, which together can enhance the usability of the form.