Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a UserControl destroy itself?

Tags:

winforms

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();
like image 685
P a u l Avatar asked Apr 11 '09 03:04

P a u l


1 Answers

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.

like image 82
Bevan Avatar answered Oct 18 '22 05:10

Bevan