Reputation: 9959
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.
Upvotes: 5
Views: 4391
Reputation: 14677
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.
Upvotes: 2
Reputation: 62256
If you subscribe to Button.Click
event, you have no much choice, as your subscript must follow relative delegate pattern. In other words, you can not add our custom parameters to even handler, as signature of your handler must match exactly the delegate type defined on the event you listen to.
So, to pass parameter:
Upvotes: 0