0

I'm writing a Windows Forms application in VS 2015.

I have part of the form that I want to change, based on a radio selection. The part that I want to change I put in a Panel control.

My current plan was to create 4 control layouts on another form. I created Form2 and created 4 panels on it. I want to copy what's in those panels from Form2 to the Panel in Form1 when the radio button is clicked.

Currently, when I click each radio button, the controls in the Form2 Panel disappear! They are maybe getting moved, not copied. The first one I click does appear on Form 1, but the others do not after that first one. I don't want Form2 (RefPanels) to be changed at all. I just want to copy what's there to Form1. Here's the code I'm trying.

//RefPanels is my Form2 instance.
public Form2 RefPanels = new Form2();

//Each Radiobutton has something similar to this.
RadioBtn1_CheckChanged(...)
{
  Control[] cArray = new Control[20];
  RefPanels.Panel1.Controls.CopyTo(cArray, 0);

  foreach (Control c in cArray)
  {
    Form1_Destination_Panel.Controls.Add(c);
  }
}

I'm sure I'm going about this all wrong. Can you help?

LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • Controls.CopyTo isn't doing a deep copy, only copying the references to the controls. That's why they are moving - when you add them to the destination panel you are adding the exiting control. – Kateract Apr 11 '16 at 16:10

2 Answers2

2

You are only copying the reference to your control. But a control can only be used in one form. So the control is dissapearing in the "old" form. You need real copies of your controls.

This Question describes a way to copy a control via reflection. Try it with a solution like this:

private void copyControl(Control sourceControl, Control targetControl)
{
    // make sure these are the same
    if (sourceControl.GetType() != targetControl.GetType())
    {
        throw new Exception("Incorrect control types");
    }

    foreach (PropertyInfo sourceProperty in sourceControl.GetType().GetProperties())
    {
        object newValue = sourceProperty.GetValue(sourceControl, null);

        MethodInfo mi = sourceProperty.GetSetMethod(true);
        if (mi != null)
        {
            sourceProperty.SetValue(targetControl, newValue, null);
        }
    }
}
Community
  • 1
  • 1
Fruchtzwerg
  • 10,999
  • 12
  • 40
  • 49
0

I would accomplish this by creating a user control for each panel that contains the controls in your desired layout. Then, when you choose a different layout, you can create a new instance of the desired user control class and add that to the correct container. This will also allow you to keep the methods and such for the controls.

Kateract
  • 822
  • 6
  • 15
  • Also add a copyData(myUCclass sourceUC) function to the UC so you can fill in the data from the source UC.. – TaW Apr 11 '16 at 17:20