C# 用于验证windows窗体中多个文本框的按键事件的公用函数

C# 用于验证windows窗体中多个文本框的按键事件的公用函数,c#,.net,winforms,C#,.net,Winforms,我们是否可以创建公共函数来检查按键事件并限制用户在windows窗体中为多个文本框只输入数字条目 我们可以创建如下内容: private void txtsample1_keypress(...) { call validate() } private void txtsample2_keypress(...) { call validate() } public void validate() { Here, validation for multiple textboxes

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

我们可以创建如下内容:

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

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

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

注意:您可能需要
IsDigit(char)
而不是
IsNumber(char)
,如中所述

注意:您可能需要
IsDigit(char)
而不是
IsNumber(char)
,如中所述


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

    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
    }

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

    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
    }
看看这里:在KeyUp而不是KeyPress中检查这个可能是个好主意…看看这里:在KeyUp而不是KeyPress中检查这个可能是个好主意。。。