0

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

4 Answers 4

2

The sender parameter contains the Control instance that generated the event.

Sign up to request clarification or add additional context in comments.

Comments

0

something like this:

private void sad(object sender, EventArgs e) {
    var buttonIndex = Array.IndexOf(u, sender);
}

1 Comment

Error:No overload for method 'IndexOf' takes 1 arguments
0

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      
}

Comments

0

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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.