|
-
Feb 17th, 2009, 12:28 PM
#1
Thread Starter
Fanatic Member
Keypress Character Validation...Code Cleanup Help
I know that this is not the best way of doing this, so I am looking for suggestions for cleaning this up. Currently, it only allows the user to enter Alpha characters, spaces, and press the enter and backspace key in a textbox.
Code:
'allow alpha characters, spacebar and backspace key only
If (e.KeyChar < "A" OrElse e.KeyChar > "z") _
AndAlso e.KeyChar <> ControlChars.Back AndAlso Asc(e.KeyChar) <> Keys.Enter AndAlso Asc(e.KeyChar) <> Keys.Space Then
'Display error message
MessageBox.Show("Only alphabetic characters are allowed in this field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
txtLastname.Focus()
e.Handled = True
End If
I need to write something to allow the following keys only:
Alpha keys, "Enter" key, "Backspace" key, "period" key, "ampersand", "spacebar" key, "apostrope" key, and "hypen" key
I want to make sure I am doing this with manage code. Thanks for any assistance.
-Jeremy
-
Feb 17th, 2009, 01:34 PM
#2
Re: Keypress Character Validation...Code Cleanup Help
you can use the Keys enum and convert them to a char for example
Code:
If e.KeyChar = Chr(Keys.Enter)
-
Feb 17th, 2009, 04:56 PM
#3
Thread Starter
Fanatic Member
Re: Keypress Character Validation...Code Cleanup Help
I have modified my code as suggested, but this method does not appear to be working. Any ideas? Thanks
Code:
'allow alpha characters, spacebar and backspace key only
If (e.KeyChar < "A" OrElse e.KeyChar > "z") _
AndAlso e.KeyChar <> ControlChars.Back AndAlso e.KeyChar <> Chr(Keys.Enter) AndAlso e.KeyChar <> Chr(Keys.Space) _
AndAlso e.KeyChar <> Chr(Keys.Subtract) AndAlso e.KeyChar <> Chr(Keys.OemPeriod) AndAlso _
e.KeyChar <> Chr(Keys.CapsLock) AndAlso e.KeyChar <> Chr(Keys.ControlKey) AndAlso e.KeyChar <> Chr(Keys.ShiftKey) _
AndAlso e.KeyChar <> Chr(Keys.NumPad8) Then
'Display error message
MessageBox.Show("Only alphabetic characters are allowed in this field.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
txtLastname.Focus()
e.Handled = True
End If
-
Feb 17th, 2009, 05:15 PM
#4
Re: Keypress Character Validation...Code Cleanup Help
Code:
Private Sub aTextBox_KeyPress(ByVal sender As Object, _
ByVal e As System.Windows.Forms.KeyPressEventArgs) _
Handles TextBox1.KeyPress, TextBox2.KeyPress
'enter all valid characters here
Dim vldCHA As String = "ABCDEF-'"
'and the special ones here
Dim specCH() As Char = New Char() {Chr(Keys.Enter), Chr(Keys.Back)}
If vldCHA.IndexOf(e.KeyChar) <> -1 Then Exit Sub
If vldCHA.IndexOf(e.KeyChar.ToString.ToUpper) <> -1 Then Exit Sub
If Array.IndexOf(specCH, e.KeyChar) <> -1 Then Exit Sub
e.Handled = True 'bad character
End Sub
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
|