0

I have the folllowing code for only numbers in the texbox, but would also like to include only numeric operations too (+,-, *, etc). How would you code for this please.

private void txtCalculation_KeyPress(object sender, KeyPressEventArgs e)
{   
    e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
001
  • 13,291
  • 5
  • 35
  • 66
tim
  • 1
  • 3

1 Answers1

0

If you only want digits and +, -, *, / you should use something like this:

private char[] validChars = {'+', '-', '*', '/'};

private void txtCalculation_KeyPress(object sender, KeyPressEventArgs e) {        
    e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar) && !Array.Exists(validChars, e.KeyChar);
}

The array validChars defines additional chars which are valid. And with the Array.Exists method you are able to check if the array contains a value specified by the second parameter of the method - in this case e.KeyChar.

whymatter
  • 755
  • 8
  • 18