Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

is there a way to do this?

like image 628
Luiscencio Avatar asked Oct 02 '09 18:10

Luiscencio


People also ask

How to Hide one form and show another in c#?

One option is to start by creating Form2 as your main form, but keep it hidden, then create and show Form1, and then when the license check is finished, close Form1 and make Form2 visible. Show activity on this post. You can show the first form using ShowDialog, which will block until the form closes.

How do I delete a panel in Visual Studio?

The first option is manual: Select all your items in the panel one by one by holding down the control key, and then when done release control, and click Ctrl+C to copy. Then delete them. You are left with the panel, so you can delete it, and paste.

How do I add controls to my panel?

Add other controls to the panel, drawing each inside the panel. If you have existing controls that you want to enclose in a panel, you can select all the controls, cut them to the Clipboard, select the Panel control, and then paste them into the panel. You can also drag them into the panel.


2 Answers

You don't give much detail as to why.

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

protected override void Dispose(bool disposing)
{
    if (disposing && (components != null))
    {
        components.Dispose();
    }

    base.Dispose(disposing);
}
like image 92
Steven Evers Avatar answered Oct 13 '22 21:10

Steven Evers


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...

like image 22
Charles Bretana Avatar answered Oct 13 '22 21:10

Charles Bretana