Search code examples
vb.netwinformstextboxtextchanged

Detecting when text in a textbox changes (while typing)


The .TextChanged event on a TextBox fires only after the TextBox loses focus. Is there a way to detect every character that is being typed while the user is typing it?

I know the radio button has a similar event called CurrentCellDirtyStateChanged to detect when the button is clicked without having to wait for it to lose focus. I was trying to find something similar for a TextBox.


Solution

  • It is not true that the TextChanged event is triggered only when the textbox loses the focus. This code

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
                                     ByVal e As System.EventArgs) _
        Handles TextBox1.TextChanged
    
        System.Diagnostics.Debug.WriteLine("TextBox1.Text = " & TextBox1.Text)
    End Sub
    

    Yields the following output (in the Output window) when typing "Hello":

    TextBox1.Text = H
    TextBox1.Text = He
    TextBox1.Text = Hel
    TextBox1.Text = Hell
    TextBox1.Text = Hello

    However, it will also fire when you delete characters, so if your intention is to filter characters use one of the key events.