C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
This method appends lines of text to a TextBox control. With it we have to deal with newlines and avoid extra line breaks. We are using the TextBox in multiline mode.
Example. We can append text to a TextBox with the method AppendText. However, that will not append a newline or line feed to the end of the text, so when you call textBox1.AppendText("text") two times, the text will be on the same line.
C# program that calls AppendText private void Test() { for (int i = 0; i < 2; i++) { textBox1.AppendText("Some text"); } } Contents of TextBox Some textSome text
Example 2. You can append lines by using Environment.NewLine and then adding some conditional logic to determine the first and last lines. This is better than any version of AppendLine or AppendText. It doesn't add extra newlines.
Tip: The Environment type offers the string value that represents a newline. It equals \r\n.
C# program that calls AppendTextBoxLine 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"); } } } Contents of TextBox Some text Some text
Example 3. If you don't check the length of the Text in the TextBox, you will have unwanted line breaks in your TextBox. However, for less important code, you may prefer the slightly simpler method. The following code always appends newlines.
Program 3: C# 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"); } } }
Discussion. The following two 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. This problem can be avoided using the method with the conditional check.
Tip: Another concept that is useful for when you want to add strings to your TextBox is appending the strings themselves.
Table 1 [Some text Some text ] Table 2 [Some text Some text]
Summary. We appended lines to a TextBox gracefully and easily with methods written in the C# programming language. These methods work well with events like TextChanged, which together can enhance the usability of the form.