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!