Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#对所有文本框应用相同的规则_C#_Textbox_Format - Fatal编程技术网

c#对所有文本框应用相同的规则

c#对所有文本框应用相同的规则,c#,textbox,format,C#,Textbox,Format,我有几个文本框,希望使用以下规则以相同的方式设置它们的格式: // limits to number, control keys, and decimal // goes to the next text box when enter private void tb_text1_KeyPress_1(object sender, KeyPressEventArgs e) { string newString = Regex.Replace(tb_text1.Text, "[^.0-9]"

我有几个文本框,希望使用以下规则以相同的方式设置它们的格式:

// limits to number, control keys, and decimal
// goes to the next text box when enter
private void tb_text1_KeyPress_1(object sender, KeyPressEventArgs e)
{
    string newString = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
    tb_text1.MaxLength = 6;
    e.Handled = (!char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar) && e.KeyChar != '.');
    if (e.KeyChar == (char)(Keys.Enter))
    {
        this.GetNextControl(ActiveControl, true).Focus();
    }
}
// removes restricted chars
private void tb_text1_Enter(object sender, EventArgs e)
{
    tb_text1.Text = Regex.Replace(tb_text1.Text, "[^.0-9]", "");
}
// applies format at exit
private void tb_text1_Leave(object sender, EventArgs e)
{
    tb_text1.Text = string.Format("{0,-6} [Ohm]", decimal.Parse(tb_text1.Text));
}
最好的方法是什么?是否基于文本框创建新的文本框类?
谢谢。

在方法中将“tb_text1”变量替换为“((TextBox)sender)”,现在您可以将代码用于任何文本框。

使用javascript很容易做到这一点。请试一试。我已经完成了,我现在找不到那段代码。这是值得努力的,因为它将非常快,并且将在客户端运行。

是的,创建一个从文本框继承的新类,并覆盖keypress事件Hnx Mohammed,仅覆盖keypress事件?似乎您已经编辑了文章,否,覆盖上面使用的所有事件您可以对所有文本框使用相同的事件处理程序,您需要:tb1.KeyPress+=tb_text1_KeyPress_1;tb2.KeyPress+=tb_text1_KeyPress_1;等