1

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!

  • You probably have lingering references to the controls, or something in them. It might not be the controls themselves. Is everything disposed properly? Events being removed? There’s many ways this could happen and most likely it’s not related to the control being a child at all. You can try by just adding and removing a `Panel`, for example, instead of a more complicated control. Dispose should be called on the control, not the collection. – Sami Kuhmonen Feb 16 '21 at 07:25
  • Dispose the Panel and assign a new Panel to `this.Panel1`. – mjwills Feb 16 '21 at 07:26
  • You need to dispose the individual controls, not the `Panel` itself. See duplicate for example of how to do that. If you dispose the `Panel`, that can work too, but then you will need to create a new one. – Peter Duniho Feb 16 '21 at 07:55

1 Answers1

3

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();
}

Carlos
  • 786
  • 7
  • 13