How can I dispose of all controls in a panel or form in ONCE ??? FROM#

Possible duplicate:
Does Form.Dispose () support call control inside Dispose ()?

is there any way to do this?

+6
c # controls dispose
source share
4 answers

Both the panel and the form class have the Controls collection property, which has the Clear () method ...

MyPanel.Controls.Clear(); 

or

 MyForm.Controls.Clear(); 

But Clear() does not call dispose() (all it does is remove it from the collection), so you need to do

  List<Control> ctrls = new List<Control>(MyPanel.Controls); MyPanel.Controls.Clear(); foreach(Control c in ctrls ) c.Dispose(); 

You need to create a separate list of links because Dispose will also remove the control from the collection by changing the index and ruining the foreach ...

+26
source share

I do not believe that there is a way to do this all at once. You can simply iterate over child controls and call each of your delete methods one at a time:

 foreach(var control in this.Controls) { control.Dispose(); } 
+1
source share

You do not give details about why.

This happens in the form's Dispose override method (in form.designer.cs). It looks like this:

 protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } 
+1
source share

You did not share if it was ASP.Net or Winforms. If the latter, you can do quite well by first typing SuspendLayout() on the panel. Then, when done, call ResumeLayout() .

0
source share

All Articles