Thea Burger's Blog

Wouldn't you like to know...

News

Photo's!!!

About me

I'm Reading: General Blogs

I'm Reading: Technical Blogs

Controls.Remove index change

Came across something now which was quite funny... I dynamically add controls to my form, and I also need the option to remove them again. So at first I did this, which seemed logic as it is exactly how I add them: 

foreach (Control c in this.Controls)
{
    
if (c.GetType() == typeof(TextBox))
    {
        
this.Controls.Remove(c);
    }
}
  
But this only removed every second textbox! At first I was dumbstruck, but then found out that when you remove a Control from the ControlCollection, subsequent controls are moved up to fill that space. So had to change it to this to work for all textboxes.  

foreach (Control c in this.Controls)
{
    
if (c.GetType() == typeof(TextBox))
    {
        forRemoval.Add((TextBox)c);
    }
}
foreach (TextBox txt in forRemoval)
    
this.Controls.Remove(txt);

 

Posted: Aug 14 2006, 09:47 PM by Thea Burger | with 3 comment(s)
Filed under: ,

Comments

Steve Campbell said:

You can do it in a single loop - when removing items from any sort of indexed container, it is always best to remove them in reverse order starting at the end. This is pretty unambiguous, easy to read, and works. By the way, when manually removing Windows controls from a container, it is best to Dispose of them at the same time. Otherwise you may have a memory leak (yes you can still have memory leaks in C#).
# August 15, 2006 7:27 PM

Thea Burger said:

Thanks for the tip!

# August 17, 2006 9:55 AM

Jeb said:

It was useful!
# October 12, 2006 7:38 PM