Reputation: 349
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;
}
Upvotes: 1
Views: 1219
Reputation: 1061
You can call txtCheckVoucher_Amount_KeyDown() from all other text boxes' KeyDown event.
Upvotes: 1
Reputation: 4127
Simple Assign same KeyDown Event txtCheckVoucher_Amount_KeyDown()
to all Textboxes
Upvotes: 0
Reputation: 9680
You can do this in three way
In general, you can retrieve the textbox control id/name by ((System.Windows.Forms.Control)(sender)).Name
Hope this helps.
Upvotes: 3
Reputation: 19526
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.
Upvotes: 1