PDA

Click to See Complete Forum and Search --> : Validating KeyPress


Bananafish
Apr 2nd, 2002, 09:56 AM
I wish to Validate entry in a textbox so that only uppercse text is entered. If Lowercase text i sentered I wish to convert it automatically to uppercase.

In vb6 - I could use the keypress event with keyascii.

For example - to convert to uppercase.

If KeyAscii >= 97 And KeyAscii <= 122 Then
KeyAscii = KeyAscii - 32
End If


Looking at .net - I can do something similar,


Private Sub txtJobCode_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtJobCode.KeyPress
If e.KeyChar.IsLower(e.KeyChar) Then
e.KeyChar.ToUpper(e.KeyChar)
End If

End Sub


but I can't figure out how to reset the key that was pressed (The above example, doesnt change what was entered in the text box).

any ideas?

ender_pete
Apr 2nd, 2002, 04:01 PM
well i ran into the same type of problem, but if all you want to do is change the text to upper case do this after they tab away or in the changetext event because the keychar, keycode, keyascii object are read only so you cant change them


txtTest.Text = txtTest.Text.ToUpper

Jop
Apr 2nd, 2002, 06:10 PM
easy, just set the e.Handled to true and the system will discard the KeyPress...
for example this would block the user from entering the character c:

Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar = "c" Then e.Handled = True
End Sub



... hmm now that I re-read your post I'm not sure if this is what you actually meant :rolleyes:

Bananafish
Apr 3rd, 2002, 02:15 AM
Thanks for the replies jop and ender_pete

I did it as ender_pete suggested in the end (in the textchanged event), although I found I had to save the position of the selectionstart property and reset it afterwards.


Dim intX As Int32 = txtJobCode.SelectionStart
txtJobCode.Text = txtJobCode.Text.ToUpper()
txtJobCode.SelectionStart = intX


Jops suggetion was useful for disallowing any character that isn't a Letter or Backspace...



If Not e.KeyChar = ControlChars.Back Then
If Not e.KeyChar.IsLetter(e.KeyChar) Then
Beep()
e.Handled = True
End If
End If


Thanks guys

Nina
Apr 3rd, 2002, 08:21 AM
there's also a new property for textboxes called CharacterCasing
it can be set to normal, upper or lower.

if set to upper, the textbox will automatically change lower case letters to uppercase

Bananafish
Apr 3rd, 2002, 08:28 AM
Thanks Nina,

I should have known there was an easy .Net way of doing it.