I'm making a windows forms application using C#. I add buttons and other controls programmatically at run time. I'd like to know how to handle those buttons' click events?
Asked
Active
Viewed 4.6k times
6 Answers
32
Try the following
Button b1 = CreateMyButton();
b1.Click += new EventHandler(this.MyButtonHandler);
...
void MyButtonHandler(object sender, EventArgs e) {
...
}

JaredPar
- 733,204
- 149
- 1,241
- 1,454
-
1thank you, but it didn't really fit my needs. I tried searching the web based on what you gave me, but I couldn't find or understand anything. Thing is, I have an array of buttons. And I'd like to know which button is clicked. – jello Jan 21 '10 at 13:19
-
@jello, did you ever find your solution to figuring out which button is clicked? I have a similar problem right now. – mdw7326 Oct 06 '14 at 12:49
23
Use this code to handle several buttons' click events:
private int counter=0;
private void CreateButton_Click(object sender, EventArgs e)
{
//Create new button.
Button button = new Button();
//Set name for a button to recognize it later.
button.Name = "Butt"+counter;
// you can added other attribute here.
button.Text = "New";
button.Location = new Point(70,70);
button.Size = new Size(100, 100);
// Increase counter for adding new button later.
counter++;
// add click event to the button.
button.Click += new EventHandler(NewButton_Click);
}
// In event method.
private void NewButton_Click(object sender, EventArgs e)
{
Button btn = (Button) sender;
for (int i = 0; i < counter; i++)
{
if (btn.Name == ("Butt" + i))
{
// When find specific button do what do you want.
//Then exit from loop by break.
break;
}
}
}

Jameel
- 1,126
- 1
- 14
- 27
3
If you want to see what button was clicked then you can do the following once you create and assign the buttons. Considering that you create the button IDs manually:
protected void btn_click(object sender, EventArgs e) {
Button btn = (Button)sender // if you're sure that the sender is button,
// otherwise check if it is null
if(btn.ID == "blablabla")
// then do whatever you want
}
You can also check them from giving a command argument to each button.

Shaokan
- 7,438
- 15
- 56
- 80
2
Check out this example How to create 5 buttons and assign individual click events dynamically in C#

Community
- 1
- 1

SwDevMan81
- 48,814
- 22
- 151
- 184
2
seems like this works, while adding a tag with each element of the array
Button button = sender as Button;
do you know of a better way?

jello
- 211
- 1
- 2
- 4
0
In regards to your comment saying you'd like to know which button was clicked, you could set the .Tag attribute of a button to whatever kind of identifying string you want as it's created and use
private void MyButtonHandler(object sender, EventArgs e)
{
string buttonClicked = (sender as Button).Tag;
}

TehSpowage
- 11
- 3