Textbox can only accept numbers

johncassell

Well-known member
Joined
Jun 10, 2007
Messages
120
Location
Redcar, England
Programming Experience
Beginner
Hi all,

can someone tell me how to restrict users to only entering numbers into a textbox.

I know it needs to be in this part but not sure what the code should be..

VB.NET:
Private Sub WorkstationTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles WorkstationTextBox.KeyPress
    End Sub

any help is greatly appreciated.

Thanks

John
 
Well i said i knew it had to be in the keypress event but that shows how much i knew..

code which worked for me...

VB.NET:
Private Sub WorkstationTextBox_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles WorkstationTextBox.KeyUp
        If Not IsNumeric(WorkstationTextBox.Text) Then
            MsgBox("This box only accepts numbers 0-9.")
        End If
    End Sub
 
Actually, spoke to soon. The way I have done it, makes a pop up box appear but when the user presses enter, it brings the box straight back up without gicing the user chance the re-enter anything.

Using the mouse to click the box gets rid of it but i'd rather not leave the user to work that out.

Any ideas anyone?

Thanks

John
 
Restrict Users only to enter numbers

The following code wont allow user to enter any characters other than numeric characters-------

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If Not IsNumeric(e.KeyChar) Then
e.Handled = True
End If
End Sub
 
why not just use the NumericUpDown control for this, then all you need to do is specify the minimum and maximum allowed
 
Back
Top