Jaebum
Jaebum

Reputation: 1570

c# when I add control to panel, the control becomes NULL

There are two forms in my project and I am trying to add the controls of Form2's panel into Form1's panel.

So,

Form2 form2 = new Form2();
new_panel = form2.Controls["panel1"] as Panel; // form2's panel 

this.panel.Controls.Add(new_panel); // add form2's panel into form1's panel.

And suddenly, the form2.Controls["panel1"] becomes NULL.

I can't understand why it happens.

Upvotes: 1

Views: 1225

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500595

A control can only have one parent - if you add a control which already has a parent to another control, it will remove itself first.

From the docs for ControlCollection.Add:

A Control can only be assigned to one Control.ControlCollection at a time. If the Control is already a child of another control it is removed from that control before it is added to another control.

If you think about it, that makes sense - a panel needs to know where it is, how big it is etc. It can really logically only be in one place at a time.

As an aside, I'd recommend using a cast rather than as when you're proceeding unconditionally as if the cast has worked - that way, if the relevant object isn't of the right type, you get an exception at the earliest moment of detection, instead of a null reference propagating itself through your system, possibly not being picked up for a long time (making it harder to diagnose the issue and introducing the possibility of data being lost).

Upvotes: 5

Related Questions