user2867445
user2867445

Reputation:

Load form's controls to panel in C#

I want to load Form's controls to a panel in C# so the panel will show the same components as the form. I have tried this code:

foreach (Control control in (new Form2()).Controls)
{
    panels[panelsCounter].Controls.Add(control);
}

But the problem is that when I'm running the program it loads only the type of control that I've added last (For example if I've been added a label and than I've added a button to the form it shows only a button, but if I add another label, it shows both of the labels, but not the button).

Please help me.

Upvotes: 0

Views: 689

Answers (2)

Hans Passant
Hans Passant

Reputation: 942328

This is a classic bug, you are modifying the collection while you are iterating it. The side-effect is that only ever other control will be moved to the panel. You'll need to do this carefully, iterate the collection backwards to avoid the problem:

var formObj = new Form2();    //???
for (int ix = formObj.Controls.Count-1; ix >= 0; --ix) {
    panels[panelsCounter].Controls.Add(formObj.Controls[ix]);
}

Upvotes: 2

Servy
Servy

Reputation: 203812

Controls are not designed to be displayed multiple times. You cannot add controls to multiple forms, or add the same control to a form multiple times. They simply weren't designed to support it.

You could go through each control and create a new control of the same type, and even copy over the values of their properties (or at least what's publicly accessible to you), effectively cloning them, but it's important that it be a different control that you add to the new panel.

Upvotes: 0

Related Questions