// First lets create a var that checks if the input is valid
private bool validInput = 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.
validInput = false;
// We are checking if it is not that valid button pressed
if (
e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9 ||
e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 ||
e.KeyCode != Keys.Oemplus || e.KeyCode != OemPeriod
){
validInput = 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 (validInput == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
// reset bool for next keydown event validation.
validInput = false;
}
}