JavaScript Editor JavaScript Editor     JavaScript Debugger

Previous Section Next Section

Main Page

Controlling Input in a Text Box

The Testing department is on the phone—there's a bug in your program! The users are getting runtime errors! Don't panic, you say; you'll be right down. You ask the user to duplicate what caused the problem—and find that they're trying to add two numbers with your program: 15553 and 955Z. What's 955Z, you ask? A typo, they say. Is there any way you can restrict user input so this doesn't happen?

Yes, you can—just use the KeyPress event and check the key that was typed, which is passed to you as e.KeyChar. For example, to check if the user is typing single digits, you might use this code:

Private Sub TextBox1_KeyPress(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.KeyPressEventArgs) _
    Handles TextBox1.KeyPress
    If (e.KeyChar < "0" Or e.KeyChar > "9") Then
        MsgBox("Please enter single digits")
    End If
End Sub

If you simply want to stop anything but digits appearing in the text box, you can set the KeyPressEventArgs Handled property to True, which indicates that we've handled the key (although we've actually discarded it):

Private Sub TextBox1_KeyPress(ByVal sender As Object, _
    ByVal e As System.Windows.Forms.KeyPressEventArgs) _
    Handles TextBox1.KeyPress
    If (e.KeyChar < "0" Or e.KeyChar > "9") Then
        e.Handled = True
    End If
End Sub

Besides the KeyPress, KeyUp, and KeyDown events, you also can use the text box's TextChanged (formerly Change) event, which occurs when there's a change in the text box's text. For example, each time the user types a key into TextBox1, you might want to echo what's in TextBox1 to TextBox2. You can do that because you're passed the object that caused the TextChanged event, which is the text box itself, so this code will work:

Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    TextBox2.Text = sender.Text
End Sub

Related solution:

Found on page:

Handling Keyboard Events

201

Previous Section Next Section




JavaScript Editor Free JavaScript Editor     JavaScript Editor