单击EventHandler:预期的方法名称和其他错误

时间:2013-07-27 15:52:38

标签: c# asp.net button event-handling

我正在使用框架版本2.0(不能使用4.0),并且以下方式将事件处理程序分配给动态创建的按钮不起作用:

deleteButton.Click += (object sender, EventArgs e) => DeleteAnswer(sender, e, toDelete);

错误:'lambda expression'不能使用它不属于ISO - 2 C#

经过一番搜索后,我尝试了这种方式:

deleteButton.Click += new System.EventHandler(DeleteAnswer(sender, e, toDelete));

错误:预计方法名称

然后这样:

deleteButton.Click += DeleteAnswer(sender, e, toDelete);

错误:无法将类型'void'隐式转换为'System.EventHandler'


这是我的代码的简短部分:

public partial class Question : System.Web.UI.Page
{

     protected void Page_Load(object sender, EventArgs e)
     {
            //Some Codes Here
           if(//Some Condition)
           {
                Button deleteButton = new Button();
                deleteButton.Click = //Event Handler Here
           }
     }

     protected void DeleteAnswer(object sender, EventArgs e, String answer)
     {
     }

}

分配事件处理程序以及传递参数的正确方法是什么?

更新

enter image description here

2 个答案:

答案 0 :(得分:3)

如果您不需要senderEventArgs参数,则可以创建一个delegate来调用您的方法。

deleteButton.Click += delegate { DeleteAnswer(toDelete); };

protected void DeleteAnswer(string answer)
{
}

否则添加签名

deleteButton.Click += delegate(object s, EventArgs e) { DeleteAnswer(s, e, toDelete); };

protected void DeleteAnswer(object sender, EventArgs e, string answer)
{
}

答案 1 :(得分:0)

您需要提供delegate namenot its signature -

deleteButton.Click+= ClickHandler;

protected void ClickHandler(object sender, EventArgs e)
{
   DeleteAnswer(sender, e, todelete);
}

protected void DeleteAnswer(object sender, EventArgs e, String answer)
{
}