tags:

views:

50

answers:

4

Why this recipe is wrong

        if (e.KeyChar <= (char)Keys.NumPad0 && e.KeyChar >= (char)Keys.NumPad2)
        {
            if (e.KeyChar <= (char)Keys.O && e.KeyChar >= (char)Keys.Oem2)
            {
                MessageBox.Show("Yes");
            }
        }

I want to be numbers between 0 and 2

+2  A: 
Keys.O

since you cannot start enum name with 0 (number zero) this must be O (letter o)

and whole logic seems flawed, it should be something like

 if ((e.KeyChar >= (char)Keys.NumPad0 && e.KeyChar <= (char)Keys.NumPad2) || (e.KeyChar => (char)Keys.Oem0 && e.KeyChar <= (char)Keys.Oem2))

(im not sure about >= and <= and Oem0)

Kikaimaru
+1  A: 

Between 0 and 2 ...

e.KeyChar >= (char)Keys.NumPad0 && e.KeyChar <= (char)Keys.NumPad2
Jonathan
People read over these things way too often :).
bastijn
+2  A: 

You are checking that it's equal or less than 0 and at the same time equal or greater than 2. That's not possible. You have to switch your greater than to less than and and vice versa, and to handle both numpad and other numeric keys, change to this:

if (e.KeyChar >= (char)48 && e.KeyChar <= (char)50)
    ...
Øyvind Bråthen
upped yours over Jonathan since it is a more complete answer.
bastijn
+1  A: 

I can't tell whether this code is present in a KeyDown or KeyPress event handler. If you want to filter typing keys then you should use KeyPress. And the code is then simply:

        if (e.KeyChar >= '0' && e.KeyChar <= '2') {
            MessageBox.Show("yes");
        }
Hans Passant