What is the best way to check for a valid numeric character in a KeyPress event?

  • Thread starter Thread starter OC
  • Start date Start date
OC said:
Is there a simple way to do this?

Here is a simple way to prevent characters that aren't spaces or
digits from being entered:

private void textBox1_KeyPress(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
e.Handled = IsInvalidInput(e.KeyChar);
}

private static bool IsInvalidInput(char c)
{
return (c < '0' || c > '9') && c != ' ';
}

HTH
 
Back
Top