TextChanged Event in WinForms

The TextChanged event is a fundamental event in Windows Forms that fires whenever the text content of a control that supports text input changes. This is commonly used with controls like TextBox, ComboBox, and RichTextBox.

Understanding the TextChanged Event

The TextChanged event is raised immediately after the text within the control has been modified. This can happen due to user input (typing, pasting) or programmatic changes to the control's Text property.

When does it fire?

When does it NOT fire?

Handling the TextChanged Event

To handle the TextChanged event, you typically subscribe an event handler method to the event. This method will be executed every time the event is fired.

Example: C#

This example demonstrates how to attach an event handler to a TextBox control named myTextBox.


using System.Windows.Forms;

public partial class MyForm : Form
{
    private TextBox myTextBox;

    public MyForm()
    {
        InitializeComponent(); // Assuming this sets up your form and controls

        // Subscribe to the TextChanged event
        myTextBox.TextChanged += new EventHandler(MyTextBox_TextChanged);
    }

    private void MyTextBox_TextChanged(object sender, EventArgs e)
    {
        // This method will be called every time the text in myTextBox changes.
        TextBox textBox = sender as TextBox;
        if (textBox != null)
        {
            // You can access the current text like this:
            string currentText = textBox.Text;
            System.Diagnostics.Debug.WriteLine("Text changed to: " + currentText);

            // Example: Update a label or perform validation
            // this.myLabel.Text = "Current input: " + currentText;
        }
    }

    // ... other form methods and designer code
}
            

Example: VB.NET

Here's the equivalent in Visual Basic .NET.


Imports System.Windows.Forms

Public Partial Class MyForm
    Inherits Form

    Private myTextBox As TextBox

    Public Sub New()
        InitializeComponent() ' Assuming this sets up your form and controls

        ' Subscribe to the TextChanged event
        AddHandler myTextBox.TextChanged, AddressOf MyTextBox_TextChanged
    End Sub

    Private Sub MyTextBox_TextChanged(ByVal sender As Object, ByVal e As EventArgs)
        ' This method will be called every time the text in myTextBox changes.
        Dim textBox As TextBox = TryCast(sender, TextBox)
        If textBox IsNot Nothing Then
            ' You can access the current text like this:
            Dim currentText As String = textBox.Text
            System.Diagnostics.Debug.WriteLine("Text changed to: " & currentText)

            ' Example: Update a label or perform validation
            ' Me.myLabel.Text = "Current input: " & currentText
        End If
    End Sub

    ' ... other form methods and designer code
End Class
            

Common Use Cases

Live Example: Character Counter

This simple example shows how to update a label with the current character count of a textbox in real-time.

Designer Code (e.g., Form1.Designer.cs)


// ... other designer code
this.myTextBox = new System.Windows.Forms.TextBox();
this.charCountLabel = new System.Windows.Forms.Label();

//
// myTextBox
//
this.myTextBox.Location = new System.Drawing.Point(12, 12);
this.myTextBox.Name = "myTextBox";
this.myTextBox.Size = new System.Drawing.Size(300, 20);
this.myTextBox.TabIndex = 0;
// Hooking up the event in designer code is often automatic
// or can be done manually like below:
// this.myTextBox.TextChanged += new System.EventHandler(this.MyTextBox_TextChanged);

//
// charCountLabel
//
this.charCountLabel.AutoSize = true;
this.charCountLabel.Location = new System.Drawing.Point(318, 15);
this.charCountLabel.Name = "charCountLabel";
this.charCountLabel.Size = new System.Drawing.Size(70, 13);
this.charCountLabel.TabIndex = 1;
this.charCountLabel.Text = "Chars: 0";
// ...
                        

Form Code (e.g., Form1.cs)


using System;
using System.Windows.Forms;

namespace WinFormsApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Ensure the event handler is hooked up if not done by designer
            if (!this.myTextBox.Equals(null))
            {
                this.myTextBox.TextChanged += new System.EventHandler(this.MyTextBox_TextChanged);
                // Initialize label on load
                UpdateCharCount();
            }
        }

        private void MyTextBox_TextChanged(object sender, EventArgs e)
        {
            UpdateCharCount();
        }

        private void UpdateCharCount()
        {
            if (this.myTextBox != null && this.charCountLabel != null)
            {
                this.charCountLabel.Text = $"Chars: {this.myTextBox.Text.Length}";
            }
        }
    }
}
                        

Performance Considerations

Be mindful of complex operations within your TextChanged event handler. Executing very slow code on every keystroke can lead to a sluggish user interface. If you need to perform intensive tasks, consider using a timer to delay the execution or debouncing techniques.

Note on Control Behavior

Some controls might have slightly different behaviors or additional events related to text changes. Always refer to the specific control's documentation for detailed information.