KeyDown事件 - 如何轻松地知道,如果按下的键是数字? [英] KeyDown event - how to easily know if the key pressed is numeric?
问题描述
我目前正在处理DataGridView控件的KeyDown事件。
其中一列是由计算的值填补,我希望用户能够重写,如果他们想要的单元值。
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...
这是相当不错的了...问题是,我觉得它难看... $代码b $ b我似乎无法找到一个巧妙的方法来处理在一个条件的所有数字键,所以我做了一个开关盒结构来应对所有可能的数字键,如下所示:
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?
所有我能找到使用谷歌是用数字键时,转换e.KeyCode为char,但是,它会给出信件甚至对数值...
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...
感谢。
推荐答案
如果您使用的KeyPress
情况下,活动签名有一个 KeyPressEventArgs
与 KeyChar
成员,让你的numberpad键的字符。您可以在这做的TryParse找出如果一个号码或没有。
If you use the KeyPress
event, the event signature has a KeyPressEventArgs
with a KeyChar
member that gives you the character for the numberpad keys. You can do a TryParse on that to figure out if its a number or not.
private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
int i;
if (int.TryParse(e.KeyChar.ToString(), out i))
{
MessageBox.Show("Number");
}
}
这篇关于KeyDown事件 - 如何轻松地知道,如果按下的键是数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!