I’m using a textbox that I want to only allow numbers and I found that this statement works.
e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
But why is it !char.IsDigit() and not char.IsDigit()? Why is it negated? Shouldn’t it be that if I enter a number, IsDigits returns true and that is what I want?
What this code is doing is saying if there is not a digit pressed and it is not a control character mark the event as handled so that further processing cannot occur.
So if a digit is pressed handled is set to false so the event passes on through and allows the normal processing logic of the keypress to occur.
As a clarification, see Edwin de Konning comments, setting Handled to True will prevent the keypresses from occuring as they mark the event as already handled. This is why the operations are a not.
The statement is logically equivalent to:
So if the character is either a digit or a control character (e.g. Ctrl+C) don’t handle the event.
This is not good enough, however, to prevent non numeric characters from being entered, because cut and paste will still work. As Edwin de Konnig suggested, you may want to look at MaskedEdit