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 :)

3 Answers 3

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

3 Comments

And a shorter example for those who cares: b.Click += (sender, e) => { var clickedButton = (Button)sender; }; =)
@Mario When you have an anonymous event handler you can avoid casting sender and just close over the button itself.
@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.
1
b.Click += delegate(object sender, EventArgs e) {
   Button clickedButton = (Button)sender; //gets the clicked button
});

1 Comment

You can simplify the syntax to just b.Click += (s, e) => { /* code */ };
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:

1 Comment

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?

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.