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() returns true if the character is a number ('0', '1', ... '9').
And e.Handled = true says "this event was already handled, so ignore it".
So your code effectively means this:
if (e.KeyChar is a number)
Ignore this event
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, as Char.IsNumber also recognizes other characters as numbers. Char.IsDigit returns true only for '0' to '9', which is most probably what you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With