Question I need help Validating my textboxes


New member
May 11, 2009
Programming Experience
Hi, i'm a beginner programmer and I have designed a form with textboxes for numerical entry. I need to validate each textbox so the number entered is an integer, and is between 0-1000. I am struggling to find how to validate the data entry. Thanks :)
I'd use the NumericUpDown control instead of Textbox.
	Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
		If Not Char.IsNumber(e.KeyChar) And Not e.KeyChar = Chr(Keys.Back) And Not e.KeyChar = Chr(Keys.Delete) Then
			e.Handled = True
		End If
	End Sub

	Private Sub TextBox1_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.Leave
		Dim num As Integer
		Integer.TryParse(TextBox1.Text, num)
		If num < 0 Or num > 1000 Then
		End If
	End Sub

Just doing it for them doesn't teach them. Can please explain the code you have so graciously provided? I know I would appreciate it. Thanks.

Sorry. I had to leave in a hurry and had no time to explain the code. The following is to be placed in the textbox's Keypress event:

If Not Char.IsNumber(e.KeyChar) 'allows only a numeric character
And Not e.KeyChar = Chr(Keys.Back) 'also allows the Backspace key
And Not e.KeyChar = Chr(Keys.Delete) Then 'and the Delete key
e.Handled = True 'will not allow a keypress if all above is Not True.

The following code goes into the texbox's Leave event. I also changed the condition to the If block. The TryParse method verifies that the text can be converted to the correct type. If not, or the textbox is empty, returns 0. It also verifies for the correct range.

Dim num As Integer
If Not Integer.TryParse(TextBox1.Text, num) Or num < 0 Or num > 1000 Then
TextBox1.Clear() 'clears the incorrect entry in the textbox
TextBox1.Focus() 'puts the cursor back in the texbox ready for a new input
End If
Last edited: