Who owns the control?

Say I have a component like this:

class SomeForm : Form
{
    private Control example;

    public void Stuff()
    {
        this.example = new ComboBox();
        // ...
        this.Controls.Add(example);
    }

    public void OtherStuff()
    {
        this.Controls.Remove(example);
    }
}

Who is responsible for the call Disposein the example control? Does this.Controlsit remove it from its removal? Or is it a leak of bundles of window handles that support controls?

(For reference, I am asking about this because I cannot see where the Windows Forms Designer generates code to call Dispose on the children of the form)

+5
source share
3 answers

Form.Dispose()will manage the controls in the collection Controls. Therefore, removing a control from Controlsit will require you to control the control yourself.

+5
source

, , , , Controls, . . , .

, . GC , finalizer/destructor, Form Dispose. , , . , () Dispose , IDisposable, .

+3

:

Form.Dispose :

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
       ... lots and lots of weird optimized checks ...
       base.Dispose(disposing);

Ok ... Formis ContainerControltherefore:

ContainerControl.Dispose:

protected override void Dispose(bool disposing)
{
    if (disposing)
    {
        this.activeControl = null;
    }
    base.Dispose(disposing);
    this.focusedControl = null;
    this.unvalidatedControl = null;
}

Grrr * ... ok, ContainerControlis Control:

Control.Dispose:

protected override void Dispose(bool disposing)
{
    ... a whole lot of resource reclaiming/funky code ...
     ControlCollection controls = (ControlCollection) 
            this.Properties.GetObject(PropControlsCollection);
     if (controls != null)
     {
         for (int i = 0; i < controls.Count; i++)
         {
              Control control = controls[i];
              control.parent = null;
              control.Dispose();
         }
         this.Properties.SetObject(PropControlsCollection, null);
      }
      base.Dispose(disposing);

So yes; the call Disposein the form will contain the controls contained in it.

0
source

All Articles