Charlie Salts
Charlie Salts

Reputation: 13488

How to remove controls from a container without container updating

I have an ordinary Panel control with a bunch of user controls contained within. At the moment, I do the following:

panel.Controls.Clear();

but this has the effect that I see (albeit quickly) each control disappearing individually.

Using SuspendLayout and ResumeLayout does not have any noticeable effect.

Question: Is there a way I can remove ALL controls, and have the container update only when all child controls have been removed?

Edit: the controls I am removing are derived from UserControl, so I have some control over their drawing behaviour. Is there some function I could possibly override in order to prevent the updating as they are removed?

Upvotes: 5

Views: 7198

Answers (2)

Charlie Salts
Charlie Salts

Reputation: 13488

Thank you Hans for your suggestion - yes, it turns out I was leaking controls.

Here's what I ended up doing:

 panel.Visible = false;

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

 panel.Visible = true;

Basically, I hide the entire panel (which is border-less) before I dispose of each control. Disposing of each control automatically removes said control from the parent container, which is nice. Finally, I make the container visible once more.

Upvotes: 9

Jodrell
Jodrell

Reputation: 35716

What I think you need is Double Buffering.

There are several answers concerning this already on SO like

Winforms Double Buffering, Enabling Double Buffering

and

How do I enable double-buffering of a control using C# (Windows forms)?

SuspendLayout stops the control redrawing as the children are removed but those actions are still processed in order when you call ResumeLayout. Double Buffering will stop the control painting at all until the offscreen buffer is updated. The update won't happen any quicker but it will be rendered to screen all at once from the buffer. If your machine is very slow you might still get a flicker when the buffer is rendered to the screen, like you would when loading a picture.

Upvotes: 0

Related Questions