Get the Key char on key down event of textbox

Prerna

New member
Joined
Mar 23, 2009
Messages
1
Programming Experience
1-3
Hi All,
I am working in vb.net.
On the KeyDown event of the textbox, i need to capture the character pressed and send it to a function which fires a sql query for this character.
To get the character i am using Convert.ToChar(e.keycode).
However Convert.Tochar converts the keycode to char according to its ASCII value , thus F4 gets converted to "s" as "s" has ASCII keycode of 115.Is there some other way to convert the keycode to character which won't make these wrong conversions as even if i restrict the functions keys there may be problem with other key conversion also.

Thanks in Advance,
Prerna
 

JohnH

VB.NET Forum Moderator
Staff member
Joined
Dec 17, 2005
Messages
15,617
Location
Norway
Programming Experience
10+
Why not get e.KeyChar from KeyPress event?
 

demausdauth

Well-known member
Joined
Mar 24, 2008
Messages
281
Location
Minnesota
Programming Experience
3-5
Not sure which characters you want or don't want so i set this up to capture all alphabetic and numbers from the top row and number pad. Ignores Ctrl and Alt combinations. The KeyPress Event might be a better way to go though.

VB.NET:
  Dim output As String = ""         
            Select Case e.KeyCode
                Case Keys.A To Keys.Z
                    If Not e.Control And Not e.Alt Then
                        If e.Shift Then
                            'upper case
                            output &= (" Case: " & Chr(e.KeyValue))
                        Else
                            'lower case
                            output &= (" Case: " & Char.ToLower(Chr(e.KeyValue)))
                        End If
                    End If
                  
                Case Keys.D0 To Keys.D9
                    output &= (" Case: " & Chr(e.KeyValue))
                Case Keys.NumPad0 To Keys.NumPad9
                    output &= (" Case: " & Chr(e.KeyValue - 48))
            End Select

It may not be the most elegant but it works.
 
Top Bottom