关于c#:Common函数,用于验证Windows窗体中多个文本框的按键事件

Common Function to validate keypress event for multiple texboxes in windows Form

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

我们能创造如下的东西吗?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
private void txtsample1_keypress(...)
{
  call validate()
}

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

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


对。

注意,您可能需要IsDigit(char),而不是IsNumber(char),正如在C中char.isdigit()和char.isNumber()之间的差异中所讨论的那样。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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;
    }
}


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

1
2
3
4
5
    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
    }