I am building a Windows Form application. I use char.IsNumber() to check the key pressed is a number or not:
private void AmBox_KeyPress(object sender, KeyPressEventArgs e)
{
if(char.IsNumber(e.KeyChar))
e.Handled=true;
}
MSDN says that char.IsNumber() checks a key char is number or not, so if it is a number it returns true. From what I’ve seen, the result is reversed – it ignores numbers(1,2,3….) instead of characters(A,a,b,c…).
I can solve the problem if I use !char.IsNumber(); but I can’t understand what this method char.IsNumber() does. Could someone kindly explain in detail?
char.IsNumber()returnstrueif the character is a number ('0','1', …'9').And
e.Handled = truesays “this event was already handled, so ignore it”.So your code effectively means this:
Looking at it this way, you probably see why your code only ignores numbers.
So the solution of using
!char.IsNumber()is correct, as it basically says “If the character is not a number, ignore this event”.Also, note that you probably are looking for
Char.IsDigit, asChar.IsNumberalso recognizes other characters as numbers.Char.IsDigitreturnstrueonly for'0'to'9', which is most probably what you want.