user2858325
user2858325

Reputation: 15

C# Clone a panel to other form

My question is very simple to explain, but it's being difficult to get the answer. I have 2 forms. In form1 I have nothing, and in form2 I have a panel with controls inside. Basically, when I click in a button from form1 I want to clone/copy the panel from form2 to form1, maintaining all it's controls and properties equal.

I already create an instance of form2 in the button click event, and made the panel public in form2.designer.cs so I can access it without opening form2. i tried to have a panel in form1 so that I would put that panel equal to the other, but didn't work. I'm out of ideas and can't find anything on the net. Can anybody help me please? Sorry for any english mistake.

Upvotes: 0

Views: 4927

Answers (1)

Matthew Layton
Matthew Layton

Reputation: 42260

Sounds like a dirty hack to me, but for what it's worth: Create a reference to form2 from form1. When you perform your "copy", you create a list of all controls on form1, and then clear form1. You then add the controls to form2.

Add this method into form1...form2 is your reference to your second form. Fire this with an event like a button click.

public void CopyControls()
{
    List<Control> ctrls = new List<Control>();
    foreach (Control c in this.Controls)
    {
        ctrls.Add(c);
    }
    this.Controls.Clear();
    form2.Controls.AddRange(ctrls.ToArray());
}

I personally wouldn't recommend doing this, it's horrid, and I bet there will be a cleaner way to achieve what you want!

Upvotes: 1

Related Questions