LabRat
LabRat

Reputation: 2014

textbox does not allow for backspace to be pressed?

I have made a textbox, which restricts character use to numbers and periods only. Nice, but now I can't enter backspace to amend any data typed in my textbox. How can I fix this?

    Private Sub TextBox10_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox10.KeyPress

    Dim allowedChars As String = "1234567890."

    If allowedChars.IndexOf(e.KeyChar) = -1 Then
        ' Invalid Character
        e.Handled = True
    End If

End Sub

Upvotes: 2

Views: 7394

Answers (1)

Miika L.
Miika L.

Reputation: 3353

You can test for backspace by using

If e.KeyChar = ChrW(8) Then
    MessageBox.Show("backspace!")
End If

So your whole code would become:

Private Sub TextBox10_KeyPress(ByVal sender As Object, ByVal e As     System.Windows.Forms.KeyPressEventArgs) Handles TextBox10.KeyPress

    Dim allowedChars As String = "1234567890."

    If allowedChars.IndexOf(e.KeyChar) = -1 andalso
            Not e.KeyChar = ChrW(8) Then
        ' Invalid Character
        e.Handled = True
    End If

End Sub

Similar question: How can I accept the backspace key in the keypress event?

Upvotes: 6

Related Questions