用于验证Windows窗体中多个文本框的按键事件的常用功能

时间:2014-09-25 15:20:59

标签: c# .net winforms

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

我们可以创建如下内容:

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

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

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

2 个答案:

答案 0 :(得分:3)

请注意,您可能需要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;
    }
}

答案 1 :(得分:1)

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

    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
    }