Search code examples
vb.nettextboxdigits

Only accept digits for textbox


I found this code for making my textbox only accept numbers.

Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    Dim allowedChars As String = "0123456789"
    If allowedChars.IndexOf(e.KeyChar) = -1 Then
        ' Invalid Character
        e.Handled = True
    End If
End Sub

But... the user can't delete the numbers using the backspace button. How do I do then?


Solution

  • You also need to handle pasted text (there may not be a keypress). The best way to do this is with a MaskedTextBox.