views:

198

answers:

4

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
What if the user right-click the textbox and pastes some text?
danbystrom
A: 

e.Handled = Not Char.IsDigit

Lala
@Lala: this does not compile as is...
Mitch Wheat
+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
Also limits user confusion. They don't get surprised when they can't type in just anything.
Matt Ellen
+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