Search code examples
c#controlsdispose

How do I dispose all of the controls in a panel or form at ONCE??? c#


Possible Duplicate:
Does Form.Dispose() call controls inside's Dispose()?

is there a way to do this?


Solution

  • Both the Panel and the Form class have a Controls collection property, which has a Clear() method...

    MyPanel.Controls.Clear(); 
    

    or

    MyForm.Controls.Clear();
    

    But Clear() doesn't call dispose() (All it does is remove he control from the collection), so what you need to do is

       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 the references because Dispose also will remove the control from the collection, changing the index and messing up the foreach...