Today, I replied to a similar post. This is also a problem that I wanted to solve when I was just learning C #. I wanted to write a "small family ledger". However, the keydown () event always determines whether the input is a non-numeric character, but cannot prevent the text box from accepting the input. The non-numeric characters are displayed.
First, I repeated the problem in vs2003.
1. added a Windows form form1 and a text box textbox1 in form1.
2. Add the following code to the keydown () event of textbox1:
Private void textbox1_keydown (Object sender, system. Windows. Forms. keyeventargs E)
{
If (E. keyValue <48 & E. keyValue> 57) // If the input character is from '0' to '9'
{
// Do nothing
}
Else
{
E. Handled = true; // If the input is a non-numeric character, the event is terminated before being added.
MessageBox. Show (E. Handled. tostring ());
}
}
Not finished. To be continued...
The example http://msdn.microsoft.com/library/chs/default.asp on msdn? Url =/library/CHS/cpref/html/frlrfsystemwindowsformscontrolclasskeydowntopic. asp
[C #]
// Boolean flag used to determine when a character other than a number is entered.
Private bool nonnumberentered = false;
// Handle the keydown event to determine the type of character entered into the control.
Private void textbox1_keydown (Object sender, system. Windows. Forms. keyeventargs E)
{
// Initialize the flag to false.
Nonnumberentered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
If (E. keycode <keys. D0 | E. keycode> keys. D9)
{
// Determine whether the keystroke is a number from the keypad.
If (E. keycode <keys. numpad0 | E. keycode> keys. numpad9)
{
// Determine whether the keystroke is a backspace.
If (E. keycode! = Keys. Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in keypress event.
Nonnumberentered = true;
}
}
}
}
// This event occurs after the keydown event and can be used to prevent
// Characters from entering the control.
Private void textbox1_keypress (Object sender, system. Windows. Forms. keypresseventargs E)
{
// Check for the flag being set in the keydown event.
If (nonnumberentered = true)
{
// Stop the character from being entered into the control since it is non-numerical.
E. Handled = true;
}
}