如何确定用户定义控件数组的单击事件
本文关键字:单击 事件 数组 控件 何确定 用户 定义 | 更新日期: 2023-09-27 18:10:08
我创建了UserControls
的Array
,其中有1个PictureBox
和1个Button
。现在我想知道哪个Button
是从UserControl
的Array
中按下的。
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?
}
sender
参数包含产生事件的Control
实例。
像这样:
private void sad(object sender, EventArgs e) {
var buttonIndex = Array.IndexOf(u, sender);
}
这应该接近您想要的效果。我可以根据你的需要修改。
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
}
我认为这是你想要的:
if (sender is UserControl)
{
UserControl u = sender as UserControl();
Control buttonControl = u.Controls["The Button Name"];
Button button = buttonControl as Button;
}