Trying to replace Controls.Clear () to avoid memory leak does not work - why?

I replaced:

panel.Controls.Clear(); 

from:

 Clear(panel); 

Where:

 public static void Clear(Control ctrl) { while (ctrl.Controls.Count > 0) ctrl.Controls[0].Dispose(); } 

And I get the following error: at Application.Run(new Form1()); System.ObjectDisposedException error was unhandled Unable to access the located object. Name of the object: "Label".

Any idea why this could be?

Thanks.

EDIT: See How to clean () controls without causing a memory leak

EDIT: Sorry, I probably dispose of what I just want to remove from my parent. I will check it. Thanks for answers.

0
source share
3 answers

I probably managed some of the Control that I used later in the code.

0
source

Dispose() has nothing for working with memory under normal circumstances. It does not free memory, does not remove an object from the collection, and does not call the garbage collector. Instead, the goal of .Dispose() is to clear resources without memory: database connections, sockets, device descriptors, gdi descriptors, etc.

The only way that can help you fix the memory problem is to use custom controls, each of which relies on code in an unmanaged (non.Net) dll.

+3
source

You need to remove the controls you have, but there may be a better approach:

 public static void Clear(Control ctrl) { foreach(Control c in ctrl.Controls) c.Dispose(); ctrl.Controls.Clear(); } 
0
source

All Articles