3
private void createButton()
{
    flowLayoutPanel1.Controls.Clear();

    for (int i = 0; i < 4; i++)
    {    
        Button b = new Button();
        b.Name = i.ToString();
        b.Text = "Button" + i.ToString();
        flowLayoutPanel1.Controls.Add(b);
    }

}
private void button1_Click(object sender, EventArgs e)
{
    createButton();
}

I Used this code to create some buttons on runtime , now how can i use those created buttons to perform diffrent actions? Im kindz new to this so please help me , very much appreciated :)

torrential coding
  • 1,755
  • 2
  • 24
  • 34

3 Answers3

8

You can assign an event handler to the click event:

b.Click += SomeMethod;

SomeMethod must have the following signature:

void SomeMethod(object sender, EventArgs e)
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
  • And a shorter example for those who cares: `b.Click += (sender, e) => { var clickedButton = (Button)sender; };` =) – Mario S Apr 18 '13 at 13:43
  • 2
    @Mario When you have an anonymous event handler you can avoid casting `sender` and just close over the button itself. – Servy Apr 18 '13 at 13:44
  • @Servy Yepp, I'm aware of that =) Just wanted to be more explicit and show what the sender is. I was guessing the OP didn't know about closures. – Mario S Apr 18 '13 at 13:47
1

When you create your button, you need to subscribe to the Click event like this :

Button b = new Button();
b.Click += new EventHandler(b_Click);
// or
b.Click += b_Click;
// or
b.Click += delegate(object sender, EventArgs e) {/* any action */});
// or
b.Click += (s, e) => { /* any action */ };

void b_Click(object sender, EventArgs e)
{
    // any action
}

This is something that is automatically done when your are is the designer in Visual Studio, and you click on a button to create the method button1_Click.
You can search in the Designer.cs of your form, you will find an equivalent line:

button1.Click += new EventHandler(button1_Click);

Related question:

Community
  • 1
  • 1
Cyril Gandon
  • 16,830
  • 14
  • 78
  • 122
  • can you please evaluate this a litle more in detail :) actually im trying to make a simple form , which creates fields as may as user wants & then the user can perform action between them , like if the user wants 2 textBox , he writes 3 & the textBox are created on runtime , & then those 2 textBox i.e textBox1 & textBox2 can get any value & the third textBox shows the added result. how to do this? – Usman Ozzie Q Qadri Apr 18 '13 at 14:55
1
b.Click += delegate(object sender, EventArgs e) {
   Button clickedButton = (Button)sender; //gets the clicked button
});
Sébastien Garmier
  • 1,263
  • 9
  • 16