|
-
Apr 23rd, 2004, 04:45 AM
#1
Thread Starter
Fanatic Member
limit textbox keypress to numeric values.
In VB6 I would limit the characters allowed in a text box by saying
VB Code:
if keyascii=??? then
keyascii=0
endif
The ??? being what ever I wanted to compare against
Now with .Net there is only a readonly keychar property.
How do I limit keypresses to numeric values.
-
Apr 23rd, 2004, 06:45 AM
#2
VB Code:
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar < "0"c Or e.KeyChar > "9"c Then
e.Handled = True
End If
End Sub
Laugh, and the world laughs with you. Cry, and you just water down your vodka.
Take credit, not responsibility
-
Apr 23rd, 2004, 06:57 AM
#3
Member
You need to use the keydown and keypress methods for each box that you are limiting. You also have to allow the - and . keys as well as all of the numpad ones.
Keydown calls this
Code:
Private Sub OnlyNumbers(ByVal e As System.Windows.Forms.KeyEventArgs)
' Initialize the flag to false.
nonNumberEntered = False
' Determine whether the keystroke is a number from the top of the keyboard.
If e.KeyCode < Keys.D0 OrElse e.KeyCode > Keys.D9 Then
' Determine whether the keystroke is a number from the keypad.
If e.KeyCode < Keys.NumPad0 OrElse e.KeyCode > Keys.NumPad9 Then
' Determine whether the keystroke is a backspace.
If e.KeyCode <> Keys.Back Then
' Determine whether the keystroke is a . or a - on either the main keyboard or keypad
If e.KeyCode <> Keys.Subtract Then 'keypad
If e.KeyCode <> Keys.Decimal Then 'keypad
If e.KeyCode <> Keys.OemPeriod Then 'keyboard
If e.KeyCode <> Keys.OemMinus Then 'keyboard
' A non-numerical keystroke was pressed.
' Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = True
End If
End If
End If
End If
End If
End If
End If
End Sub
This goes within keyPress:
Code:
' Check for the flag being set in the KeyDown event.
If nonNumberEntered = True Then
' Stop the character from being entered into the control since it is non-numerical.
e.Handled = True
End If
Hope that helps
Jim
-
Apr 23rd, 2004, 07:27 AM
#4
Thread Starter
Fanatic Member
Now thats more complicated than it used to be.
Thanks.
-
Apr 23rd, 2004, 10:31 AM
#5
Thread Starter
Fanatic Member
yaksplat
Your code doesn't work at all, I can type anything and everything in the textbox.
crptcblade
Yours is too good, I forgot to mention that I need to allow the backspace button to be pressed.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|