is there a way to add and remove controls from a form to another without the controls being deleted/GCed?
I have one form called:
MyControlContainerForm ccf
and a main form called:
SolidForm sf
and I am adding all the controls inside an instance of new MyControlContainerForm ()
to SolidForm
, using:
sf.Controls.Add ( Control )
but when I remove them using:
sf.Controls.Remove ( Control )
they are gone from MyCont开发者_开发技巧rolContainerForm
instance as well.
Why? And how do I prevent this?
I want to be able to add MyControlContainerForm
controls whenever I want, without initializing MyControlContainerForm
every time, just once.
The reason this is happening is not that you're removing the controls from form2, but rather that you're adding them. Controls can't be shared between forms. If you look at the reflected code of the form2.Controls.Add() on the Control Collection enumerator, we can see what's happening here:
... if (value.parent == this.owner) { value.SendToBack(); } else { if (value.parent != null) { value.parent.Controls.Remove(value); } base.InnerList.Add(value); ...
As you can see here it check the parent of the incoming control, if it's not the owner of the collection, then it simply runs a value.parent.controls.Remove(value) to strip the control from it's originating form, so it can be added to the current one.
Controls are not intended to be on 2 Forms at the same time. Im surprised you got way with that, probably because you do not Show MyControlContainerForm .
Note that Control has a Parent property (= in who's Controls collection am I?), singular.
Edit:
In fact, when button1 is on panel1, it is part of panel1.Controls. But the statement
panel2.Controls.Add(button1);
removes button1 from panel1.Controls.
You can use a List<Control>
as a store. That would also keep them alive just fine.
精彩评论