Click here to Skip to main content
15,919,479 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am attempting to break down user input onto a KeyDown event on a DataGrid by working out whether their input is a letter or a number.

The method I am using at the moment performs bizzarely. Firstly, the IsDigit never happens and clearly is not working. Secondly the IsLetter works, but only on some letters (W,Z,X,V and Y). There must be a more comprehensive way of doing this as this clearly is not working for me.

What I have tried:

This is the method I am using so far;

private void OnDataGridKeyDown(object sender, KeyEventArgs e)
{
   if (char.IsLetter(Convert.ToChar(e.Key)))
   {
        MessageBox.Show("Letter");
   }
   if (char.IsDigit(Convert.ToChar(e.Key)))
   {
        MessageBox.Show("Number");
   }
}
Posted
Updated 7-Sep-16 0:01am
v2
Comments
Richard MacCutchan 7-Sep-16 5:23am    
Convert.ToChar does not work on key values. You also need to look at the documentation for KeyEventArgs, which does not list a property named Key.
Thanks to Griff for setting me right.
OriginalGriff 7-Sep-16 5:33am    
The WPF version does - and DataGrid is a WPF control.
Richard MacCutchan 7-Sep-16 5:38am    
Curse you Microsoft.

1 solution

Convert.ToChar does not have an overload which explicitly takes a Key value, so quite what it will produce I'm not certain. It's unlikely to convert Key.A to 'A', Key.B to 'B' and so forth.
In fact, I just checked:
C#
System.Windows.Input.Key k = System.Windows.Input.Key.A;
for (int i = 0; i < 26; i++)
    {
    char c = Convert.ToChar(k);
    Console.WriteLine("{0}:{1}", k, c);
    k++;
    }
And it doesn't:
A:,
B:-
C:.
D:/
E:0
F:1
G:2
H:3
I:4
J:5
K:6
L:7
M:8
N:9
O::
P:;
Q:<
R:=
S:>
T:?
U:@
V:A
W:B
X:C
Y:D
Z:E

What you need to do is:
C#
Key k = e.Key;
if (k >= Key.A && k <= Key.Z)
    {
    ...
    }
if ((k >= Key.D0 && k <= Key.D9) || (k >= Key.NumPad0 && k <= Key.NumPad9))
    {
    ...
    }
 
Share this answer
 
v2
Comments
Richard MacCutchan 7-Sep-16 5:41am    
I sometimes think upvoting you is like carrying coals to P O'H's house. But I still do occasionally.
OriginalGriff 7-Sep-16 5:48am    
:laugh:
I know what you mean.
DRD94 7-Sep-16 6:06am    
Thankyou!
OriginalGriff 7-Sep-16 6:46am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900