Hi all!
I've got a performance problem. In my application, I need to add/remove some
user controls at run-time inside a panel. My problem is that I can't use the
foreach statement to enumerate the controls to remove them.
For example: if I use this code, it throws me an exception:
foreach( Control c in mypanel.Controls )
{
myPanel.Controls.Remove(c);
}
The exception is raised because I try to modify the collection
myPanel.Controls that is used in the foreach statement. So, I solved this in
this way, that is using a for statement with an index starting from the end
to the start of the collection.
for( int i = myPanel.Controls.Count - 1; i >= 0; i-- )
{
myPanel.Controls.Remove(myPanel.Controls[i]);
}
This way works. My question is: is this the right way to do or there is some
better ways?
Another problem: performace. Doing so, everything works, but it's really
slow and looks bad because you can see the controls disappearing slowly one
by one. What I'd like to do is lock the panel UI, remove all the controls
that need to bo removed, and then unlock the panel UI to show it refreshed
at the end of the removing process. I think that if I am able to do this, I
will get a great performance improvement and also a good looking. I tried
the SuspendLayout()/ResumeLayout() calls but they didn't change anything at
all. Any idea?
Thanks.
Matteo Galletti.
Jeff Gaines - 04 Dec 2006 16:07 GMT
On 04/12/2006 in message <uyn9xr7FHHA.4588@TK2MSFTNGP05.phx.gbl> Magallo
wrote:
>The exception is raised because I try to modify the collection
>myPanel.Controls that is used in the foreach statement. So, I solved this
[quoted text clipped - 8 lines]
>This way works. My question is: is this the right way to do or there is
>some better ways?
I usually do it in 2 stages. First go through and add the controls to an
ArrayList then go through the ArrayList and delete the controls there. It
may be worth trying so you can compare the speed?

Signature
Jeff Gaines