【问题标题】:Common Function to validate keypress event for multiple texboxes in windows Form用于验证 Windows 窗体中多个 texbox 的按键事件的常用函数
【发布时间】:2014-11-20 10:35:55
【问题描述】:

我们可以创建通用函数来检查按键事件并限制用户在 windows 窗体中为多个文本框输入数字条目吗?

我们可以创建如下所示的内容吗:

private void txtsample1_keypress(...)
{
  call validate()
}

private void txtsample2_keypress(...)
{
  call validate()
}

public void validate()
{
  Here, validation for multiple textboxes
}

【问题讨论】:

标签: c# .net winforms


【解决方案1】:

是的。

请注意,您可能需要IsDigit(char) 而不是IsNumber(char),如Difference between Char.IsDigit() and Char.IsNumber() in C# 中所述。

public void Form_Load(object sender, EventArgs e)
{
    txtsample1.KeyPress += ValidateKeyPress;
    txtsample2.KeyPress += ValidateKeyPress;
}

private void ValidateKeyPress(object sender, KeyPressEventArgs e)
{
    // sender is the textbox the keypress happened in
    if (!Char.IsDigit(e.KeyChar)) //Make sure the entered key is a number (0-9)
    {
        // Tell the text box that the key press event was handled, do not process it
        e.Handled = true;
    }
}

【讨论】:

    【解决方案2】:

    当然,您甚至可以在所有文本框中注册相同的事件并通过一个处理它们。

        void txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsNumber(e.KeyChar)) //Make sure the entered key is a number
                e.Handled = true; //Tells the text box that the key press event was handled, do not process it
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 2010-10-08
      • 1970-01-01
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多