I have several TextBoxes which need to allow only numeric inputs. The problem is I have to copy & paste the code below for another TextBox that allows only numeric values. Is there any simpler way to implement? such as using functions or inheritance?
private void txtCheckVoucher_Amount_KeyDown(object sender, KeyEventArgs e)
{
if (Control.ModifierKeys == Keys.Shift)
{
e.SuppressKeyPress = true;
return;
}
if (((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) ||
(e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
e.KeyCode == Keys.Decimal || e.KeyCode == Keys.OemPeriod ||
e.KeyCode == Keys.Back || e.KeyCode == Keys.Tab ||
e.KeyCode == Keys.Left || e.KeyCode == Keys.Right ||
e.KeyCode == Keys.End || e.KeyCode == Keys.Home ||
e.KeyCode == Keys.ShiftKey || e.KeyCode == Keys.Delete))
{
}
else if (e.KeyCode >= Keys.A || e.KeyCode <= Keys.Z)
e.SuppressKeyPress = true;
}
If the textboxes need the same KeyDown event logic, why not just subscribe both textboxes to the same event handler?
You can just set the KeyDown event to the same txtCheckVoucher_Amount_KeyDown() method.