I have a panel which displays Form objects. When the Close() method is called on a form, the panel.Controls.Count is modified, the Count is one less. How is this possible?
This is the way I show a form in th panel:
// insertForm is a windows form
insertForm.TopLevel = false;
insertForm.Dock = DockStyle.Fill;
insertForm.FormBorderStyle = FormBorderStyle.None;
this.pnlContent.Controls.Clear();
this.pnlContent.Controls.Add(insertForm);
And when somewhere form.Close() is called, the Controls count of pnlContent is 0. So, how is this possible? What all happens when Close() is called?
Closing a form causes the form to be disposed, which in turn causes it to be removed from its parent’s control-collection.
If you use a decompiler, you will notice two things:
ControlCollection, the control’s owner is set as theControlCollection'sowner.ControlCollection.Add(Control value)callsvalue.AssignParent(this.owner).ControlCollection. Essentially,Control.Disposecallsparent.Controls.Remove(this).Lesson learned: Don’t use a ControlCollection as general purpose collection-type for Controls. It is deeply integrated into WinForms for control-containment and parent-child relationships. Use this type only when you genuinely require a parent control to contain a child control.