简体   繁体   中英

Copying Panels from one Form to another in C#

I'm replicating a panel with subpanels As shown in the following pic:

一个面板中有5个面板

I use the following code to construct a new Form and try to fill the panel in that form.

public Form3(Panel p)
{
    InitializeComponent();

    foreach(Panel child in p.Controls){
        panel1.Controls.Add(child);
    }
}

but what ends up happening is as the child gets added, the original Panel starts getting deleted and loses controls.

In the end it skips every other control like in the following picture.
The left side is the original Panel and the right side is the panel in the new form.

在此处输入图片说明

How should I go about doing this? I want the original and the new panel to have the exact same controls. In fact, I don't even know why it's deleting it from the original Panel.

PS Inside the constructor I've made sure to see if the original panel that's being passed in has the correct values and they do.

When you add a control to a parent it will automatically remove it from its previous parent. Then only it will add to new parent.

Control provides a property Parent . If you add a control in two panels the what yould you expect the control.Parent to return? First parent or second?

You need something like this

foreach(Panel child in p.Controls)
{
    panel1.Controls.Add(new Panel{ BackColor = child.BackColor });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM