how do i set the properties of a text box so that the user can only enter numbers?
thanks,
marvin
Printable View
how do i set the properties of a text box so that the user can only enter numbers?
thanks,
marvin
use something like this:
VB Code:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress If Not Char.IsDigit(e.KeyChar) Then e.Handled=True End If End Sub
That way would allow you to check as they were entered. You could also use regular expressions to validate it in the Validating event. If you didnt want to check every character as it is entered, code something up in the validating event (either a RegEx or something else) and if its not a number (IsNumeric returns false is another way to check) then show a msgbox and set cancel = true.
lol .Quote:
Originally posted by MikeStammer
That way would allow you to check as they were entered. You could also use regular expressions to validate it in the Validating event. If you didnt want to check every character as it is entered, code something up in the validating event (either a RegEx or something else) and if its not a number (IsNumeric returns false is another way to check) then show a msgbox and set cancel = true.
I wouldn't bother with RE just to allow numbers . The code lunatic3 posted is good . Another way is here :
I bet on that . :)VB Code:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress 'Numeric keys start with 48 through 52 'backspace key has the ascii code 8 'period key has the ascii code 46 Dim KeyAscii As Integer KeyAscii = Asc(e.KeyChar) 'only disallow numeric values Select Case KeyAscii Case Asc("0") To Asc("9") 'acceptable keystrokes e.Handled = True ' Case Asc(".") if you want to disable 'other keys 'e.Handled = True Case Else e.Handled = False End Select End Sub
the only problem i can see here is if the user copies n' pastes a string containing numeric chars directly into the textbox you wish to validate. So i would go with something in the text_changed event or suchlike.
Cheers...
my thoughts exactly! Thats what validate event is for, to validate things!
Simply Intercept Copy & Paste Messages with API .Quote:
Originally posted by MikeStammer
my thoughts exactly! Thats what validate event is for, to validate things!