I have a textbox which controls 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!
+3
A:
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
Mitch Wheat
2009-11-15 03:23:05
What if the user right-click the textbox and pastes some text?
danbystrom
2009-11-15 17:31:29
+4
A:
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.
MiseryIndex
2009-11-15 03:49:05
Also limits user confusion. They don't get surprised when they can't type in just anything.
Matt Ellen
2009-11-15 16:47:36
+2
A:
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
Hans Passant
2009-11-15 16:35:38