Search code examples
c#user-controls

pass picture from usercontrol to Form


I have a main form with 1 panel, the panel has 10 user controls and every user control has on picture box.

Main form:

private void Form1_Load(object sender, EventArgs e)    
{

    Picturebox1.Image=....

    for(int i=0;i<10;i++)
    {
        uscontrol a=new uscontrol()
        {
            usimage=Image.Fromfile....  
        };
        panel1.Controls.Add(a);
    }
}

User control:

public Image usimage
    {
        get { return imagebox.Image; }
        set { imagebox.Image = value; }
    }

How can I do that when I click on one of the user controls, it passes image of that user control to main form and shows it in Picturebox1, thank you.


Solution

  • Firstly, you will need to add MouseClickEvent to every uscontrol. To achieve that, edit your Form1_Load to this.

    Picturebox1.Image=....
    for(int i=0;i<10;i++)
    {
        uscontrol a=new uscontrol()
        {
            usimage=Image.Fromfile....  
        };
        a.MouseClick += new MouseEventHandler(USControl_Clicked); //Note this added line 
        panel1.Controls.Add(a);
    }
    

    And then you will need to add USControl_Clicked to your From1 code.

    private void USControl_Clicked(object sender, MouseEventArgs e)
    {
        //Here we cast sender to your uscontrol class and access usimage
        Picturebox1.Image = (sender as uscontrol).usimage; 
    }