Disposing controls

G

Guest

I guess I'm not exactly sure when or how to dispose controls when I
dynamically add/remove controls.

Let's say I have a user control, and whenever a certain button is
pressed, I delete all the controls on the user control and add a bunch
of new controls to it. Do I really need to Dispose all of the controls
that are being removed?

I assume that we are supposed to dispose them, but what kind of
problems might realistically occur if they are not disposed.

Do controls such as Forms or Panels dispose all the controls that are
in their Controls collection when they are disposed?

Thanks.
 
N

Nick Hounsome

I guess I'm not exactly sure when or how to dispose controls when I
dynamically add/remove controls.

Let's say I have a user control, and whenever a certain button is
pressed, I delete all the controls on the user control and add a bunch
of new controls to it. Do I really need to Dispose all of the controls
that are being removed?

I assume that we are supposed to dispose them, but what kind of
problems might realistically occur if they are not disposed.

You are asking the wrong question.
What kind of problem cannot occur if they are not disposed?
It is never documented why you need to call dispose for each control
therefore you have to assume that there is a good reason. Even if there
isn't one in this version MS are perfectly entitled to add one in the next.
It is best programming practice to always expect the worst in these cases.
Do controls such as Forms or Panels dispose all the controls that are
in their Controls collection when they are disposed?

Just look at the code generated when you create a new form in the designer.

P.S. I don't know exactly what you are trying to acheive but it might be
better to just set Visible=false rather than delete and add controls.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top