Reputation: 39
I have created an Array
of UserControls
which have 1 PictureBox
and 1 Button
. Now I want to know which Button
is pressed from the Array
of UserControl
.
UserControl u=new UserControl[20];
for (int j = 0; j < 20; j++)
{
u[j] = new UserControl();
u[j].BringToFront();
flowLayoutPanel1.Controls.Add(u[j]);
u[j].Visible = true;
u[j].button1.Click+=new EventHandler(sad);
}
private void sad(object sender, EventArgs e)
{
//how to determine which button from the array of usercontrol is pressed?
}
Upvotes: 0
Views: 479
Reputation: 1078
I think this gets you what you want:
if (sender is UserControl)
{
UserControl u = sender as UserControl();
Control buttonControl = u.Controls["The Button Name"];
Button button = buttonControl as Button;
}
Upvotes: 0
Reputation: 4182
This should do close to what you want. I can modify as needed to suit your case.
FlowLayoutPanel flowLayoutPanel1 = new FlowLayoutPanel();
void LoadControls()
{
UserControl[] u= new UserControl[20];
for (int j = 0; j < 20; j++)
{
u[j] = new UserControl();
u[j].BringToFront();
flowLayoutPanel1.Controls.Add(u[j]);
u[j].Visible = true;
u[j].button1.Click +=new EventHandler(sad);
}
}
private void sad(object sender, EventArgs e)
{
Control c = (Control)sender;
//returns the parent Control of the sender button
//Could be useful
UserControl parent = (UserControl)c.Parent; //Cast to appropriate type
//Check if is a button
if (c.GetType() == typeof(Button))
{
if (c.Name == <nameofSomeControl>) // Returns name of control if needed for checking
{
//Do Something
}
}
//Check if is a Picturebox
else if (c.GetType() == typeof(PictureBox))
{
}
//etc. etc. etc
}
Upvotes: 0
Reputation: 7092
something like this:
private void sad(object sender, EventArgs e) {
var buttonIndex = Array.IndexOf(u, sender);
}
Upvotes: 0
Reputation: 887469
The sender
parameter contains the Control
instance that generated the event.
Upvotes: 2