Removing controls on the fly

  • Thread starter Thread starter Safiiru no Baka
  • Start date Start date
S

Safiiru no Baka

Hi I'm having issues removing controls on the fly. Here's my code:
=================================================================
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();

for(int i = 0; i < this.Controls.Count; i++)
{
System.Windows.Forms.Control tempText;
tempText = this.Controls;

if(tempText is System.Windows.Forms.TextBox)
{
this.Controls.Remove(tempText);
tempText.Dispose();
}

}
//
// TODO: Add any constructor code after InitializeComponent call
//
}
=================================================================

It is working somewhat, some text boxes are removed while some are not.
I tried directly using the "this.Controls" handle but that behaves
the same way, except different fields are left behind.

Thanks in advance.
 
Hint: Modifying a collection while iterating through it is probably not a
good idea...

In your case, every time you remove a textobox, the next control doesn't get
a look in.

See this for a hack:
http://www.danielmoth.com/Blog/2005/02/hack-prevent-enumerator-throwing.html

If you cannot redesign so you can do the removal outside the loop (and also
avoid the slow Remove method that does a full iteration every time), then
walk the loop backwards i.e.
for (int i = this.Controls.Count-1; i >=0 ; i--)

(note, in my hack solution on my blog, iterating backwards was not an option
for other reasons but in your case it should be fine)

Cheers
Daniel
 
Hi, thanks for the replies.

I figure i'd update the solution i found. The call to Controls.Count
was changing every iteration as I called Controls.Remove so the loop
was being cut off.

Also... once you remove a Control the indexing of all controls "shift"
down to fill the gap so that was screwing things up as well.

Indexing backwards might do the trick however! One last question
however, what do you mean with "Remove" being slow? Thanks again.
 
however, what do you mean with "Remove" being slow? Thanks again.
Not much more to expand on that. The Remove method on collections (e.g.
ArrayList) performs badly. RemoveAt is much faster. So wherever possible I
try to use the latter when I know the index (like in this case).

Cheers
Daniel
 
Back
Top