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);
}
Johnny Mopp
  • 12,641
  • 5
  • 36
  • 62
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
  • 693
  • 9
  • 14