Embedd_0913
Embedd_0913

Reputation: 16555

How to set list items to null C#?

I have a user control called container in which I am adding other user controls at run time.

I want to remove all controls from container, I am doing container.Controls.Clear() but my controls are still in memory, how can I make them null ?

Upvotes: 4

Views: 1055

Answers (3)

Devin
Devin

Reputation: 1064

Calling Dispose() on the parent container will also dispose all of its children controls assuming they also implement IDisposable. Generally speaking, all WinForms controls will implement IDisposable so this should work.

If they don't (as is the case with WPF since WPF controls don't implicitly use unmanaged code), you'll need to add some custom cleanup method to your controls. One of the most common sources of memory leaks is undetached event handlers. I usually do something like the following:

public void CleanUp()
{
    //detach event handlers
    //other cleanup as necessary
}

this is especially helpful if you make this virtual and add it to a base class that your user controls will inherit, therefore you can simply invoke CleanUp() without having to check the type. I personally like this method rather than implementing IDisposable since IDisposable is largely for cleaning up unmanaged resources.

Upvotes: 1

Pranay Rana
Pranay Rana

Reputation: 176896

Suppose panel is you parent control which contains all child control , so loop through all child controls and call dispose method of each...that might resolve your issue

  while (panel.Controls.Count > 0)
  {
     panel.Controls[0].Dispose();
  } 

Calling clear method just remove your controls from the container control not from the memory so you need to dispose them...

Upvotes: 4

ericosg
ericosg

Reputation: 4965

Calling the Clear method does not remove control handles from memory. You must explicitly call the Dispose method to avoid memory leaks.

read more: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.clear.aspx

Upvotes: 8

Related Questions