1

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
}

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.