0

我创建了Array其中一个UserControls1PictureBox和 1 Button。现在我想知道从ofButton中按下的是哪个。ArrayUserControl

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?
}
4

4 回答 4

2

sender参数包含Control生成事件的实例。

于 2013-04-19T19:15:45.023 回答
0

像这样的东西:

private void sad(object sender, EventArgs e) {
    var buttonIndex = Array.IndexOf(u, sender);
}
于 2013-04-19T19:16:00.807 回答
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      
}
于 2013-04-20T01:31:43.583 回答
0

我认为这会让你得到你想要的:

    if (sender is UserControl)
    {
        UserControl u = sender as UserControl();

        Control buttonControl = u.Controls["The Button Name"];
        Button button = buttonControl as Button;
    }
于 2013-04-20T02:21:28.617 回答