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?
When I have had the requirement of an input which only accepts numbers, I have typically used the
NumericUpDown
class. It handles limits and decimals too.Use this code, it will help you
You also need to handle pasted text (there may not be a keypress). The best way to do this is with a MaskedTextBox.