John
John

Reputation: 1338

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.

Upvotes: 1

Views: 8414

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112762

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.

Upvotes: 5

user2836518
user2836518

Reputation:

You could use the KeyDown or KeyPress events. These will fire whenever you press a key.

Upvotes: 3

Related Questions