【问题标题】:Text Box User Control in C# Windows Application?C# Windows 应用程序中的文本框用户控件?
【发布时间】:2013-05-17 04:22:33
【问题描述】:

在我的用户控件中,我有一个文本框,它只接受数字的验证。我将此用户控件放在我的表单上,但 Keypress 事件未在表单中触发。以下是我的用户控件中的代码

    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        base.OnKeyPress(e);
        if (this.KeyPress != null)
            this.KeyPress(this, e);
    }
 private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar!=(char)Keys.Back)
        {
            if (!char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }
    }

但在表单中我也希望按键事件触发但它没有触发

public Form1()
    {
        InitializeComponent();
        txtNum.KeyPress += new KeyPressEventHandler(txtPrprCase1_KeyPress);
    }

    void txtPrprCase1_KeyPress(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show("KeyPress is fired");
    }

但它没有开火。我不明白我想做什么?这对我来说很紧急。

【问题讨论】:

  • 请告诉我你的TextBox 代码。
  • 它已经在那里了,第一个是用户控件文本框
  • 我想要你的textboxHTML 代码
  • 我是 Windows 开发者,不是 web

标签: c# user-controls textbox keypress onkeypress


【解决方案1】:

不需要以下覆盖:

protected override void OnKeyPress(KeyPressEventArgs e)
{
    base.OnKeyPress(e);
    if (this.KeyPress != null)
        this.KeyPress(this, e);
}

因为base.OnKeyPress(e); 将触发附加事件。您无需手动操作。

改为在文本框的事件处理程序中调用用户控件的OnKeyPress

private void txtLocl_KeyPress(object sender, KeyPressEventArgs e)
{
    base.OnKeyPress(e);

    if (e.KeyChar!=(char)Keys.Back)
    {
        if (!char.IsDigit(e.KeyChar))
        {
            e.Handled = true;
        }
    }
}

【讨论】:

    【解决方案2】:

    尝试将事件处理程序代码放入您的 Form_Load 事件中,或使用表单设计器创建事件处理程序(它位于属性页面上的闪电图标中)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2011-10-17
      • 2011-05-22
      • 2012-08-22
      相关资源
      最近更新 更多