VB: Allowing Only Numbers (not Letters) To Be Entered Into Textbox
I have a textbox which 开发者_如何学Pythoncontrols the interval of a Timer control. How do I filter out letters? Is it possible to restrict entry to numbers only (like if you enter a letter or a space, nothing happens)? Is there a property of the textbox that can accomplish this? Thanks!
Is replacing the textbox with another control an option? In my experience I found the NumericUpDown control easier to work with if you want to restrict input to numeric values only.
It also has cute up and down arrows, but best of all, it requires no extra code.
Ignores all but digits
Private Sub TextBox1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
e.Handled = Not Char.IsDigit(e.KeyChar)
End Sub
Filtering keys hardly guarantees that the user will input a valid number. A time interval of 0 is probably no good. You won't be filtering input when the user pressed Ctrl+V. And as a programmer, I'm partial to programs that accept 2E3 as valid input.
The Validating event was made to solve this. Drop a couple of text boxes on a form and an ErrorProvider:
Private Sub TextBox1_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
If TextBox1.Text.Length = 0 Then Exit Sub
Dim value As Double
If Not Double.TryParse(TextBox1.Text, value) or value <= 15 or value > 1E6 Then
TextBox1.SelectAll()
ErrorProvider1.SetError(TextBox1, "Not a valid number")
e.Cancel = True
Else
TextBox1.Text = value.ToString("N0")
ErrorProvider1.SetError(TextBox1, "")
Timer1.Interval = CInt(value)
End If
End Sub
e.Handled = Not Char.IsDigit
You can filter out the specific keys. This method will only allow numbers, delete, backspace, left arrow, and right arrow
Private Sub txtBox_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles yourTxtboxName.KeyDown
Try
If Not (e.KeyValue = 8 Or e.KeyValue = 46 Or e.KeyValue = 48 Or e.KeyValue = 49 Or e.KeyValue = 50 Or e.KeyValue = 51 Or e.KeyValue = 52 Or e.KeyValue = 53 Or e.KeyValue = 54 Or _
e.KeyValue = 55 Or e.KeyValue = 56 Or e.KeyValue = 57 Or e.KeyValue = 96 Or e.KeyValue = 97 Or e.KeyValue = 98 Or e.KeyValue = 99 Or _
e.KeyValue = 100 Or e.KeyValue = 101 Or e.KeyValue = 102 Or e.KeyValue = 103 Or e.KeyValue = 104 Or e.KeyValue = 105 Or e.KeyValue = 37 Or e.KeyValue = 39) Then
e.SuppressKeyPress() = True
End If
Catch ex As Exception
'error handling
End Try
精彩评论