2

I have a FlowLayoutPanel inside the main form and the FlowLayoutPanel is filled with UserControls (of type UCProducts).

My UserControl has a PictureBox and an object (of Product Class).

UserControl: (simplified):

public partial class UCProducts : UserControl
{
    public Product product;
    public UCProducts(Product product)
    {
        InitializeComponent();
        this.product = product;
    }
}

Form:

for (int i = 0; i < SomeList.Count; i++)
{
    uCProducts = new UCProducts(SomeList[i]);
    uCProducts.ptcbProduct.Click += new EventHandler(uCProducts_click);
    flpClothing.Controls.Add(uCProducts);
}

When the PictureBox is clicked, I want to access the product object inside the UCProducts from the Form. I tried to do it with the new event handler, but I couldn't.

This is how I tried:

void uCProducts_click(object sender, EventArgs e)
{
    PictureBox tempPic = (PictureBox)sender;
}

Can Sender send UserControl directly? How can I pull the product object in the form?

1 Answers1

1

One way would be to access the UserControl via the Parent property of the PictureBox control. Then, you can access its product member as you would normally do:

void uCProducts_click(object sender, EventArgs e)
{
    PictureBox tempPic = (PictureBox)sender;
    UCProducts ucProducts = tempPic.Parent as UCProducts;
    Product theProduct = ucProducts.product;
}

You probably should convert product into a property though. Also, try to stick to the standard naming conventions.