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

后端 未结 8 1881
天命终不由人
天命终不由人 2020-12-19 03:00

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 va

相关标签:
8条回答
  • 2020-12-19 03:51

    Just get the last char from the Key that will be number if a number was pressed. This method works with KeyDown events not needing any other conditions.

    Just call this static method and pass in the Key to check

    public static bool IsNumber(Keys key)
    {
      string num = key.ToString().Substring(key.ToString().Length - 1);
      Int64 i64;
      if (Int64.TryParse(num, out i64))
      {
        return true;               
      }
      return false;
    }
    
    0 讨论(0)
  • 2020-12-19 03:54

    On the msdn help page they use this code in their example:

    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    

    ...

    // Determine whether the keystroke is a number from the keypad.
    if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
    
    0 讨论(0)
提交回复
热议问题