Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing Arguments to a Method in EventHandler

This question has been asked many times but the solution is not working for some reason.

I am dynamically creating a Button and assigning an EventHandler to it.

protected void Page_Load (object sender, EventArgs e)
{
    Button b = new Button();
    b.Click += new EventHandler(Method);
}

protected void Method (object sender, EventArgs e)
{
   //Do work here
}

I needed to pass an argument so the most simple way I thought of was this:

b.Click += new EventHandler(Method(sender, e, "name"));

protected void Method (object sender, EventArgs e, String name)
{
   //Do work here
}

Error: Method name expected

So after checking the questions here, I found the same solution in almost every question.

b.Click += new EventHandler((sender, e) => Method(sender, e, "name"));

Error: A local variable named "sender" cannot be declared in this scope because it would give a different meaning to "sender", which is already used in a 'parent or current' scope to denote something else.

So I changed to the following:

b.Click += new EventHandler((sender1, e1) => Method(sender1, e1, "name"));

And the error from Visual Studio was gone, but upon running the webpage, I received this error:

System.ArgumentOutOfRangeException: Index was out of range. Must be a non-negative and less than the size of the collection.

What's the problem here I'm really lost.

like image 963
Ali Bassam Avatar asked Nov 03 '22 19:11

Ali Bassam


1 Answers

Your declaration of adding Eventhandler to custom method is correct. The source of error is something else. Look at the CallStack when you're getting this exception and see what is the actual source of your error.

like image 144
vendettamit Avatar answered Nov 08 '22 15:11

vendettamit