KeyPress Event :
Now we will check if the pressed key isnumeric or not. The code will something be like this
if (!char.IsNumber(e.KeyChar) )
If the pressed key is not numeric character, it should not be appear in the textbox. To do so we have to handle the Backspace key. Actually the character will appear in the textbox and we will fire a code to delete the last typed character. To delete the last character we have to handle backspace key. Here is the code
e.Handled = e.KeyChar != (char)Keys.Back;
Here is the complete code :
if (char.IsNumber(e.KeyChar))
{
return;
}
else
{
e.Handled = e.KeyChar != (char)Keys.Back;
}
If you want to allow fraction value, you should allow a dot (.) also. To do so you can use the code below.
if (char.IsNumber(e.KeyChar) || e.KeyChar == '.')
{
return;
}
else
{
e.Handled = e.KeyChar != (char)Keys.Back;
}
One more thing. You may noticed that we used e.KeyChar == '.' instead of e.KeyChar == "."
"." used to set a string value. But we are checking a character, not comparing nor setting a sting value. So we will use '.'
To watch this on youtube :
https://www.youtube.com/watch?v=T1fIKGBmBGc
No comments:
Post a Comment