我创建了Array
UserControls
个PictureBox
和1 Button
。现在我想知道Button
Array
中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?
}
。
{{1}}
答案 0 :(得分:2)
sender
参数包含生成事件的Control
实例。
答案 1 :(得分:0)
类似的东西:
private void sad(object sender, EventArgs e) {
var buttonIndex = Array.IndexOf(u, sender);
}
答案 2 :(得分:0)
这应该接近你想要的。我可以根据需要进行修改以适应您的情况。
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
}
答案 3 :(得分:0)
我认为这可以满足您的需求:
if (sender is UserControl)
{
UserControl u = sender as UserControl();
Control buttonControl = u.Controls["The Button Name"];
Button button = buttonControl as Button;
}