Reputation: 31
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 :)
Upvotes: 3
Views: 3050
Reputation: 17048
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:
Upvotes: 1
Reputation: 1263
b.Click += delegate(object sender, EventArgs e) {
Button clickedButton = (Button)sender; //gets the clicked button
});
Upvotes: 1
Reputation: 174309
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)
Upvotes: 8