-2

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. 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");
    }
}

However, this 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.

CBreeze
  • 2,925
  • 4
  • 38
  • 93

1 Answers1

1

There is difference between key.toChar() and char which you expect to be there. You can read about conversion here but it's not simple one:

how to capture the '#' character on different locale keyboards in WPF/C#?

layonez
  • 1,746
  • 1
  • 16
  • 20
  • @thomas-ayoub added how to use it in current context – layonez Sep 07 '16 at 08:30
  • Why would one re-implement `char.IsLetter()` and `char.IsDigit()` when it already exists and works well? – Thomas Ayoub Sep 07 '16 at 08:38
  • You right bro, there is another problen in that question – layonez Sep 07 '16 at 08:59
  • `char.IsLetter(Convert.ToChar(Keys.A)) => true` this **should** work, without more information from OP, there is no way to help – Thomas Ayoub Sep 07 '16 at 09:01
  • The main problem here is that the event he's are catching is keyboard event and that the key is indeed a key and NOT a character. For example, when typing shift-A, you will receive two event instead of one for keypressed. – layonez Sep 07 '16 at 09:04
  • And the event handling `Shift` will not log anything while the event handling `A` should log *Letter*. Let's wait for OP – Thomas Ayoub Sep 07 '16 at 09:06