Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char.IsNumber()

Tags:

c#

winforms

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?

like image 698
user1366440 Avatar asked May 13 '26 00:05

user1366440


1 Answers

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.

like image 117
Botz3000 Avatar answered May 14 '26 13:05

Botz3000