CS0123 - 'TextChanged'没有重载匹配委托'EventHandler'

时间:2018-05-27 17:51:04

标签: c# winforms

完全披露是的,这是家庭作业,是的,我已经尝试研究我的问题,但仍然没有得到如何解决它。

所以我试图只允许将数字输入文本框。我是使用KeyPressEventArgs参数完成的。

private void classAinput_TextChanged(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar))
        e.Handled = true;
    else
    {
        invalidFormatError();

    }
    e.Handled = true;
}

这对我来说效果不错,但我收到CS0123错误说:

  

'classAinput_TextChanged'没有重载与委托相匹配   '事件处理'

设计师代码内部。

这是为什么?

// 
// classAinput
// 
this.classAinput.Location = new System.Drawing.Point(67, 51);
this.classAinput.Name = "classAinput";
this.classAinput.Size = new System.Drawing.Size(100, 20);
this.classAinput.TabIndex = 4;
this.classAinput.TextChanged += new System.EventHandler(this.classAinput_TextChanged);
// 

完整表格1代码:https://hastebin.com/husececuri.cs

2 个答案:

答案 0 :(得分:0)

您的问题是您目前正在向TextChanged提供错误的方法。 TextChanged事件需要objectEventArgs类型作为参数。由于您的目标是捕获按键事件,请删除当前方法,将其添加到表单中:

 private void classAinput_KeyPressed(object sender, KeyPressEventArgs e)
 {
    if (!char.IsDigit(e.KeyChar))
        e.Handled = true;
    else
    {
        invalidFormatError();

    }
    e.Handled = true;
 }

在您的设计师身上,它将是:

this.classAinput.KeyPressed += new System.EventHandler(this.classAinput_KeyPressed);

答案 1 :(得分:0)

TextChanged事件不接受KeyPressEventArgsKeyPress确实如此,所以请订阅:

this.classAinput.KeyPress += new System.KeyPressEventHandler(this.classAinput_TextChanged);

或者,您可以使用int.TryParse事件尝试TextChanged。实现可能是这样的:

private void classAinput_TextChanged(object sender, EventArgs e)
{
    if (!(classAinput.Text == "" || int.TryParse(classAinput.Text, out int _))) {
        invalidFormatError();
    }
}
相关问题