How can UserControl destroy itself?

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

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

And, if the parent needs to destroy the control, what are the steps? This is what I still have:

  Controls.Remove(control); control.Dispose(); 
+7
winforms
source share
2 answers

You work in a managed garbage collection environment — there is nothing you can do to force a user control to be destroyed.

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

Usually this will be enough:

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

The only time you need more is to associate events with events, as you will also need to unregister.

+6
source share

The control cannot destroy itself. As for the parent, you are on the right track. You can have a parent or other Dispose control call on it and remove all links to this control. Allocating control in this way will allow the GC to clear things.

0
source share

All Articles