简体   繁体   English

如何以更好的方式使用KeyDown事件验证?

[英]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 您可以通过三种方式进行

  1. You can have common function which will check the entered key is valid or not. 您可以使用通用功能来检查输入的密钥是否有效。 And you call that function from all key down event handlers. 然后从所有关键事件处理程序中调用该函数。 This is suitable if you have textbox on different forms. 如果文本框的格式不同,则此方法适用。
  2. If all the text boxes are on same form, in that case, bind all key down event handler to same function. 如果所有文本框的格式相同,则将所有按键事件处理程序绑定到同一函数。
  3. You can have your custom textbox control which will accept only required keys. 您可以使用自定义文本框控件,该控件仅接受必需的键。 Check this post, it might help you. 查看这篇文章,可能会对您有所帮助。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM