Code
Code

Reputation: 356

How to dynamically create EventHandlers for dynamically created buttons? C# VS2010

so, I have a form that is dynamically populated with textboxes and buttons. How can I create EventHandlers for each of those buttons dynamically (ex: it generates 20 buttons, I need 20 eventhandlers). Each button will have the same function (to delete something from a database) but I need the program to know whenever any one of them is clicked to trigger that code. // also, the button creation code is within a while() so I can't use it ouside that while (just pointing that out) Code:

public void LoadElements()
{
    //more code here
    while(some condition)
        {
            // more code above
                Button b = new Button();
                                b.Text = "Delete";
                                b.Name = "button" + j;
                                b.Location = new Point(240, Y);
                                Controls.Add(b);
            // more code bellow
        }
    // more code here
}

Upvotes: 1

Views: 714

Answers (2)

Vaughan Hilts
Vaughan Hilts

Reputation: 2879

Assign them like you would for any other event in your code. You can simply add an event handler doing something like:

b.Click += b_Click

Upvotes: 2

Raging Bull
Raging Bull

Reputation: 18737

Add in the loop:

b.Click+=New Eventhandler(b_Click);

(Just press TAB twice after typing b.Click+=).

Define the function b_Click outside of the loop. It will be invoked when anyone of those button is clicked.

Upvotes: 1

Related Questions