The easiest way I know to do this is to keep users from entering nonnumeric data to begin with. Try this:
Declare a form level boolean:
private bool nonNumPressed = false;
Capture the KeyDown event for the editbox and add this code:
private void OnKeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumPressed = false;
// see if the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// see if the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// see if 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.
nonNumPressed = true;
}
}
}
}
Capture the KeyPress event and enter this code:
private void OnKeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumPressed == true)
{
// stop the non-numeric character from being entered into the textbox.
e.Handled = true;
}
}
Now there is nothing to validate because you know that only numbers were entered. Now set the MaxLength property to 8 and you're good to go.
You could easily create your own numeric textbox control by inheriting from the TextBox control and adding this code. Drop it in your toolbox and it will be ready to go whenever you needed it.