tags:

views:

55

answers:

1

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 MyControlContainerForm 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.

+2  A: 

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.

highphilosopher