views:

57

answers:

1

I seem to have some weird issue going on that I am sure will turn out to be a simple thing. I have a Windows Form and on the form I have 1 panel called MainPanel and inside MainPanel, I got another panel with a button inside and a label that is inside MainPanel, but not in the second panel. 2 controls. What I am trying to do is copy all the controls inside MainPanel over to another panel object. I am using the following C# code to do this:

GUIPanel gp = new GUIPanel();
foreach (System.Windows.Forms.Control ctrl in gp.Controls["MainPanel"].Controls)
{
    m_OptionsControl.Controls.Add(ctrl);
}

When I run this code, it copies over the panel with the button, but not the label. What's even more odd is when I set a breakpoint and run it through the debugger, and I type "?gp.Controls["MainPanel"].Controls.Count" in the immediate window, it returns 2, just like it should. However, when stepping through the code, it only executes the foreach loop once. What am I missing here?

+1  A: 

WinForms controls cannot be copied; your code will not work correctly.
When you add the control to the second panel, it will be removed from the first panel.

You can move all of the controls using a reverse for loop.
You can copy the controls by creating a new instance of each control and copying over all of the properties.

EDIT: For example:

for (int i = MainPanel.Controls.Count - 1; i >= 0; i--) {
    MainPanel.Controls[i].Parent = m_OptionsControl;
}
SLaks
Moving is what I want. Do you have an example of what you mean by a reverse for loop?
icemanind
@icemanind: Here you go.
SLaks
Don't you mean i-- ?
John JJ Curtis
@Jeff: Yes, I do.
SLaks