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.
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: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
aswhen 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 anullreference 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).