VB: Allowing Only Numbers (not Letters) To Be Entered Into Textbox

13,187

Solution 1

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.

Solution 2

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

Solution 3

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
Share:
13,187
David
Author by

David

Updated on June 04, 2022

Comments

  • David
    David almost 2 years

    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!