Keep in mind that the above method will disallow the use of the backspace key, as well as (I think) the delete and arrow keys. I wrote some code that transformed a textbox into a numbers-only textbox:
- /// <summary>
-
/// Processes the data entered into a textbox to determine if it is numeric.
-
/// </summary>
-
/// <param name="KeyCode">The KeyCode that was typed into the textbox.</param>
-
/// <returns>False if the value entered was numeric, otherwise true.</returns>
-
private bool suppressKeyPress(Keys KeyCode)
-
{
-
if (KeyCode < Keys.D0 || KeyCode > Keys.D9 &&
-
KeyCode < Keys.NumPad0 || KeyCode > Keys.NumPad9)
-
{
-
if (KeyCode != Keys.Back &&
-
KeyCode != Keys.Delete &&
-
KeyCode != Keys.Left &&
-
KeyCode != Keys.Right)
-
{
-
return true;
-
}
-
}
-
-
if (Control.ModifierKeys == Keys.Shift)
-
return true;
-
-
return false;
-
}
The method will return a boolean, true if the keypress should be ignored, false otherwise. Use this method in a KeyDown event handler. I believe you'll have to set your form's KeyPreview property to true for it to work. Within the event handler, simply set the KeyEventArgs.SupressKeyPress property to the return of the above method (which you have to pass a KeyCode value to, get the KeyCode from the KeyEventArgs for the handler).
I think I covered everything, let me know if you need more help.