[英]How to use of KeyDown Event Validation in a better way?
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.
问题是我必须将下面的代码复制并粘贴到另一个仅允许数字值的TextBox中。 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;
}
You can do this in three way 您可以通过三种方式进行
In general, you can retrieve the textbox control id/name by ((System.Windows.Forms.Control)(sender)).Name
通常,您可以通过
((System.Windows.Forms.Control)(sender)).Name
来检索文本框控件的ID /名称((System.Windows.Forms.Control)(sender)).Name
Hope this helps. 希望这可以帮助。
If the textboxes need the same KeyDown event logic, why not just subscribe both textboxes to the same event handler? 如果文本框需要相同的KeyDown事件逻辑,为什么不将两个文本框都订阅到同一事件处理程序呢?
You can just set the KeyDown event to the same txtCheckVoucher_Amount_KeyDown() method. 您可以将KeyDown事件设置为相同的txtCheckVoucher_Amount_KeyDown()方法。
您可以从所有其他文本框的KeyDown事件中调用txtCheckVoucher_Amount_KeyDown()。
简单地将相同的KeyDown事件txtCheckVoucher_Amount_KeyDown()
分配给所有文本框
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.