Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

c# - KeyDown event - how to easily know if the key pressed is numeric?

I am currently handling the KeyDown event of a DataGridView control. One of the columns is filled by calculated values and I want the user to be able to override the cell value if they want.

When the user presses a numeric key, the cell goes into EditMode and allows the user to override the value. If the key is not numeric, nothing happens...

That is working pretty well... the problem is that I find the code for it ugly... I can't seem to find a neat way to handle all the numeric keys in a single condition, so I've made a switch case construct to deal with all the possible numeric keys, like this:

                switch (e.KeyCode)
                {
                    case Keys.D0:
                    case Keys.D1:
                    case Keys.D2:
                    case Keys.D3:
                    case Keys.D4:
                    case Keys.D5:
                    case Keys.D6:
                    case Keys.D7:
                    case Keys.D8:
                    case Keys.D9:
                    case Keys.Decimal:
                    case Keys.NumPad0:
                    case Keys.NumPad1:
                    case Keys.NumPad2:
                    case Keys.NumPad3:
                    case Keys.NumPad4:
                    case Keys.NumPad5:
                    case Keys.NumPad6:
                    case Keys.NumPad7:
                    case Keys.NumPad8:
                    case Keys.NumPad9:

                         [code to make the cell go to editMode, etc...]

Sure, it works, but there has to be a better and shorter way, right?

All I could find using Google is converting e.KeyCode to a char, but when using numeric keys, it goes gives letters even for the numeric values...

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try

if ((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
    (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
    e.KeyCode == Keys.Decimal)
{
    // Edit mode
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...