Reputation: 60691
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar < '0' || e.KeyChar > '9')
if (e.KeyChar != '\b')
e.Handled = true;
}
i am not understanding how this code is not allowing anything except backspace and numbers.
e.Handled=True
do?Upvotes: 6
Views: 12291
Reputation: 8993
1 and 2: It's actually the other way around. This is saying that "if the key is not 0-9, then check if it is backspace. If it is not backspace, then e.Handled is true."
3: When e.Handled is set to true the control, parent form, and whatever other thing listening to capture the key press will NOT do anything. e.Handled basically says, "It is taken care of, no one else worry about it."
Upvotes: 2
Reputation: 1499770
The first if
statement is basically saying if it is a digit, allow it to proceed as normal - otherwise go into the second if
statement.
The second if
statement is saying that if it's also not backspace, allow it to proceed as normal - otherwise go onto the assignment statement.
e.Handled = true;
indicates that the event handler has already processed the event and dealt with it, so it doesn't need to be processed any further. In other words, please don't take any further action.
Here's an alternative way of writing the same body:
bool isDigit = e.KeyChar >= '0' && e.KeyChar <= '9';
bool isBackspace = e.KeyChar == '\b';
// If we get anything other than a digit or backspace, tell the rest of
// the event processing logic to ignore this event
if (!isDigit && !isBackspace)
{
e.Handled = true;
}
Upvotes: 15
Reputation: 754525
What this code is doing is setting e.Handled=true
when the character is
Upvotes: 1