tags:

views:

342

answers:

2

When the user clicks on certain part of a window, I add a UserControl to the window's controls. The UserControl has a close button. What can I do in the UserControl's button handler to destroy the UserControl? There seems to be no .net analog to the Win32 DestroyWindow call, and there is no Close() method for a control. So far I have this:

private void sbClose_Click(object sender, EventArgs e)
{
    Parent.Controls.Remove(this);
    this.Dispose();
}

And, in case the parent needs to destroy the control, what are the steps? This is what I have so far:

    Controls.Remove(control);
    control.Dispose();
+2  A: 

You're working in a managed code environment with garbage collection - there's nothing you can do to force the user control to be destroyed.

All you need to do, all you can do is to remove it from the parent and make sure there are no remaining references.

This will generally be sufficient:

private void sbClose_Click(object sender, EventArgs e)
{
    Parent.Controls.Remove(this);
}

The only time you'll need more is if you tie things together with events, as you'll need to deregister those as well.

Bevan
Not just control/managed related. Objects destroying themselves? fun!
Chad Grant
A: 

A control can't destroy itself. In terms of having a parent do it, you are on the right track. You can have the parent or another control call Dispose on it and remove all references to this control. Dereferencing the control this way will allow the GC to clean things up.

adeel825