C# TextBox.AppendText MethodCall the AppendText method on TextBox controls to add lines of text.
TextBox.AppendText. TextBox provides the AppendText method. 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.
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.
private void Test() { for (int i = 0; i < 2; i++) { textBox1.AppendText("Some text"); } }
Some textSome 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. This code always appends newlines.
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
Discussion. 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. 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.
String Append
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"); } } }
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.
Table 1:
[Some text Some text ]
[Some text Some text]
© 2007-2022 sam allen.
see site info on the changelog.