Key Validation

P

Paul Paiva

In the VB6 days I was successfully able to validate the keys typed into a
text box, to allow only numeric keys, or whatever the need was. I would
simply trap for those values in KeyCode or KeyAscii in the key_down or
key_press events. When I wanted to disallow a given key, I would set the
value of KeyCode or KeyAscii to zero.

In dot net, I'm finding that it is doesn't work quite the same way. I've
tried a few techniques but no avail. I'm thinking there is some basic
concept I am missing. If anyone has some basic key validation code that
would be helpful, or can you point me in the right direction.

Thanks
Paul
 
E

Ed Kaim [MSFT]

One way to do this is to handle the KeyPress event on the TextBox. If you
want to block a character, you can set the "Cancelled" property of the
KeyPressEventArgs parameter to true. For example, this code would ignore all
"a"s:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

If e.KeyChar = "a" Then

e.Handled = True

End If

End Sub
 
P

Paul Paiva

Awesome. Works great. Thank!

Ed Kaim said:
One way to do this is to handle the KeyPress event on the TextBox. If you
want to block a character, you can set the "Cancelled" property of the
KeyPressEventArgs parameter to true. For example, this code would ignore all
"a"s:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

If e.KeyChar = "a" Then

e.Handled = True

End If

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top