2

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
rmtheis
  • 5,992
  • 12
  • 61
  • 78
LabRat
  • 1,996
  • 11
  • 56
  • 91

1 Answers1

6

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?

Community
  • 1
  • 1
Miika L.
  • 3,333
  • 1
  • 24
  • 35