-1

so what i am trying to do is on button_Click to copy all Controls from (template)panel into a new panel. Here's my code:

           private void button6_Click(object sender, EventArgs e)
    {
        Panel myPanel = new Panel();
        myPanel.Location = new Point(25, 25);
        Control[] controls = new Control[panel1.Controls.Count];
        panel1.Controls.CopyTo(controls, 0);
        foreach (Control c in controls)
            myPanel.Controls.Add(c);
    }

But unfortunatelly on button_Click my template Panel just dissapears and i new Panel doesn't appears.

Can some one say me, where in code i have made a mistake ?

dave
  • 19
  • 2
  • Does this answer your question? [How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?](https://stackoverflow.com/questions/3419159/how-to-get-all-child-controls-of-a-windows-forms-form-of-a-specific-type-button) and [Clone Controls - C# (Winform)](https://stackoverflow.com/questions/10266589/clone-controls-c-sharp-winform) –  Jun 20 '21 at 17:37
  • 2
    Build a UserControl instead. – Jimi Jun 20 '21 at 22:21

1 Answers1

0

and i new Panel doesn't appears.

You seem to have forgotten to add myPanel to the form...

this.Controls.Add(myPanel); 

Keep in mind that the CopyTo in your code will make a shallow copy. Therefore if the references of the "template" controls are copied multiple times, there will be an entanglement problem, and possibly an unwanted behavior, unless this "copy" is done only once. Indeed, the method CopyTo simply copies the array of references without deep cloning.

Caius Jard
  • 72,509
  • 5
  • 49
  • 80
  • This copies nothing? and I don't understand the complaint that the source panel disappears, but that is more likely explained away that something else happens to it in some other place.. I addressed the question of why the new panel does not appear- simply that it is never put into the control hierarchy. It is created, has controls copied to it, then it is simply discarded when flow leaves the click event handler – Caius Jard Jun 20 '21 at 17:51
  • 1
    Oh, I thought you were talking about my code! Feel free to edit the answer if you want to point it out more clearly – Caius Jard Jun 20 '21 at 20:19