【问题标题】:Cannot implicitly convert type 'System.EventHandler' to 'System.Windows.Forms.KeyPressEventHandler' in C# [duplicate]无法在 C# 中将类型“System.EventHandler”隐式转换为“System.Windows.Forms.KeyPressEventHandler”[重复]
【发布时间】:2021-08-11 15:54:33
【问题描述】:

我正在尝试制作一个只接受数字的文本框。

    private void depositTextBox_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;
        }

    }

这是在设计器中。

    this.depositTextBox.KeyPress += new System.EventHandler(this.depositTextBox_KeyPress); 

其他错误。

    No overload for 'depositTextBox_KeyPress' matches delegate 'EventHandler'

【问题讨论】:

  • 小数点分隔符不是点怎么办?如果键入多个分隔符怎么办?如果只输入符号而无法解析有效数字怎么办?如果通过热键/Windows 消息/上下文菜单粘贴了某些内容怎么办?我看到的所有纯数字文本框都存在缺陷且笨拙。相反,使用验证。更简单也更清洁。或者简单地将 TextBox 绑定到 int/float/decimal 属性或 DataTable 列,一切都会按预期工作。

标签: c# winforms textbox event-handling keypress


【解决方案1】:

这是因为KeyPressKeyPressEventHandler 类型的事件,而不是您尝试使用的EventHandler(请参阅代码中的new System.EventHandler)。

要么使用new System.Windows.Forms.KeyPressEventHandler 的正确类型,要么直接使用this.depositTextBox.KeyPress += this.depositTextBox_KeyPress; 分配方法,这样更简单

更准确地说,错误实际上发生在 System.EventHandler 构造函数中,因为它需要签名 void methodName(object, EventArgs) 的方法,而您的方法是签名 void mehtodName(object, System.Windows.Forms.KeyEventArgs)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-31
    • 2020-04-23
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多