System.Windows.Forms.Textbox AppendLine

appendline

Ever wanted to append a new line of text to a TextBox, tried searching IntelliSense for a AppendLine method but just couldn’t find it?

With the following code, one can add the missing AppendLine(string text) method for appending a new line of text to a System.Windows.Forms.TextBox by using the new Extension Methods of C# 3.0

using System;
using System.Windows.Forms;

namespace cSouza.Utils.WinForms
{
   
public static class TextBoxExtender
    {
       
/// <summary>
        ///  Appends a new line of text to the current text of the TextBox.
        /// </summary>
        /// <param name="text">The text to append to the current contents of the TextBox</param>
       
public static void AppendLine(this TextBox textBox, String text)
        {
            if (textBox.Text.Length > 0)
                textBox.AppendText(Environment.NewLine)
;
            textBox.AppendText(text)
;
       
}

        /// <summary>
        ///  Inserts a new line to the current text of the TextBox.
        /// </summary>
        /// <param name="text">The text to append to the current contents of the TextBox</param>
       
public static void AppendLine(this TextBox textBox)
        {
            textBox.AppendText(Environment.NewLine)
;
       
}
    }
}

To use AppendLine() on a TextBox object, just add this class to your project and import its namespace. To do this, create a new empty class, copy and paste this code inside it and then import the cSouza.Utils.WinForms namespace (with the using directive) wherever needed. Feel free to change the namespace name to something else if you wish.

Once this class becomes reachable from your code, you’ll notice that AppendLine() will start showing up on IntelliSense right after you type in the name of a TextBox object, just like a standard method would.

For more information about the new Extension Methods of C# 3.0, you can read a nice article written by Vipul Patel on developer.com by clicking here.

Leave a Reply

Your email address will not be published. Required fields are marked *