Dynamically add handler for a button click event

946 views Asked by At

How can I add a handler for the click event of every single generated button?

For example:

Button btn = new Button();
btn.ID = "delete_" + i.ToString();

btn.Click += degerate
{
     callFunction(i);
};

Whenever I try pressing the button, it'll only affect calling the function for the last inserted click event. Any suggestions for a fix?

2

There are 2 answers

2
João Vitor Cabral On

Within the loop you used to declare your buttons, use the following snippet:

button.Click += new EventHandler(<funcName>);

Don't forget that "funcName" must match the EventHandle delegate.

Then all your buttons will share the same Event Code, but each event is bound to it's own button.

You can access all info of each button, by casting the sender as the specific object type you're using, for example:

Button btn = (Button)sender;
btn.ID = <new value>;
1
GreenRibbon On

If the code you have above all gets executed every time you want to add a click handler, you are creating a brand new button object each time. Because it is a totally new object, it knows nothing about the click handlers attached to older buttons.