C# How to remove a control collection from memory

369 Views Asked by At

I use a Panel to load controls from different forms into the MainForm.

Form1 Form1_loaded = new Form1() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
Form1_loaded.FormBorderStyle = FormBorderStyle.None;                  
this.Panel1.Controls.Add(Form1_loaded);

This works, no problem. Then I d like to load another controls, let's say from Form2.

 this.Panel1.Controls.Clear();
 Form2 Form2_loaded = new Form2() { Dock = DockStyle.Fill, TopLevel = false, TopMost = true };
 Form2_loaded.FormBorderStyle = FormBorderStyle.None;                  
 this.Panel1.Controls.Add(Form2_loaded);

At this point, it works fine. But the problem is that the Clear() method does not remove the controls from the memory. Therefore When I get to 10.000 control ( from what I read it's the limitation), loading back and forth between the different forms controls, I will get a unhandled Error. Even impossible to handle with a try/catch.

Then I read that I should use the Dispose() method. However, if I use Panel1.Dispose() , then it disappears completely and I can't get it to load other controls anymore. And If I use this.Panel1.Controls.Dispose() Control.ControlCollection does not contain a definition for 'Dispose'.

Thanks everyone!

1

There are 1 best solutions below

0
On BEST ANSWER

The first problem is that Clear() does not call Dispose() of the controls, it only removes them from the Panel.

The second one is that you are disposing the panel not the controls that is why it disappears.

So, try first removing the controls and then disposing them:

while (this.Panel1.Controls.Count > 0)
{
   var control = this.Panel1.Controls[0];
   this.Panel1.Controls.RemoveAt(0);
   control.Dispose();
}