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?C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.
C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.
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;
}
What this code is doing is setting e.Handled=true
when the character is
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."
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