0

我需要处理我的文本框的按键事件,以便用户在文本框中仅输入数字数据,我的代码工作正常,我将其发布在下面,但我担心的是,我有 30 多个相同的文本框要求,我不想为 30 个文本框的按键事件编写相同的代码,但我不能在方法中编写此代码并调用该方法..有什么办法可以解决这个问题,以便我可以编写代码在一个地方,并在文本框的按键事件或任何其他使我的代码看起来标准并减少行数的方式中调用它,我在下面发布我的代码

        if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.')
        {
            e.Handled = true;
        }

        // only allow one decimal point
        if (e.KeyChar == '.'
            && (sender as TextBox).Text.IndexOf('.') > -1)
        {
            e.Handled = true;
        }
4

1 回答 1

1

当然,您可以为所有文本框使用一个事件处理程序

TextBox tb = new TextBox();
tb.KeyPress += tb_KeyPress;

TextBox tb2 = new TextBox();
tb2.KeyPress += tb_KeyPress;

  void tb_KeyPress(object sender, KeyPressEventArgs e)
  {
        if (!char.IsControl(e.KeyChar)
    && !char.IsDigit(e.KeyChar)
    && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // only allow one decimal point
    if (e.KeyChar == '.'
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }
  }
于 2013-03-26T09:33:28.720 回答