Link to home
Start Free TrialLog in
Avatar of slightlyoff
slightlyoff

asked on

Clear the Runtime-Created Controls from a Panel vb.net

How do I clear the a variety of controls I created inside of a Panel?

In side the panel, I load (at runtime) a series of text boxes, lables, radio buttons and checkboxes, when the user clicks on a ListView item.  if the user clicks on a different listview item, I need the contents of the panel cleared out - deleted, so that I can redraw the new controls that pertain to that listview item.

Hope this makes sense!

Thanks for your help!
Avatar of Sylvain Drapeau
Sylvain Drapeau
Flag of Canada image

Hello !

should be easy :

For each ctl as Controls in panel1.controls
    panel1.controls.remove(ctl)
next

Syldra
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of slightlyoff
slightlyoff

ASKER

Thanks!  That worked perfectly.
Sorry for not responding earlier, but there's an important fact you should know : The Clear method does not remove control handles from memory, that may lead to memory leaks. That's why I use the Remove method.

Simpler does not always mean better...

Syldra
"The Clear method does not remove control handles from memory"

What?....

The controls that are removed will no longer have any references to them (assuming none were explicitly stored somewhere else) and they will AUTOMATICALLY be GARBAGE COLLECTED.

.Net has always done this...where are you getting your information from Syldra?
Is MSDN a good enough source ?

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.clear(v=VS.100).aspx

It's been like this since .Net 2.0... you have to call the Dispose method manually.

That's what I understand... I might be wrong.

But as they say, I'd rather be safe than sorry.

Syldra
That's funny how the documentation states that you have to call Dispose() on the controls in the collection but then doesn't do it in the example provided right there on MSDN...  =\

The Remove() method probably doesn't dispose of a control either though...what if you just wanted to remove it but add it back in later?

I just tried both methods and couldn't see any decrease or difference in memory usage, handle count, or gdi object count between the two.

I even tried this:

        While Panel1.Controls.Count > 0
            Panel1.Controls(0).Dispose()
        End While
        GC.Collect()
        GC.WaitForPendingFinalizers()

...and the memory usage dropped slightly but the handle count and gdi object count held steady...but there was also no increase in count for these values when the dynamic controls were created and added to the form.

Thanks for pointing out the documentation but I can't see any difference...