Search code examples
c#winformsforeachdispose

Deleting all controls on a Winform with a foreach loop


Possible Duplicate:
C# Not Disposing controls like I told it to

I use this to delete all Pictureboxes I created on my Winform

foreach (PictureBox pb in this.Controls)
{
    pb.Dispose();
}

but each time only about the half of all Pictureboxes get disposed, the other half remains untouched

i solved it by surrounding it with a while (Controls.OfType<PictureBox>().Count() > 0 ) Loop so it just gets executed until all Pictureboxes are gone, but this is a bad solution and i want to know why this happens and how i can solve it the right way


Solution

  • Control.Dispose is removing the control from the collection, changing the index and messing up the foreach.

    You can solve this problem by using a reverse for loop or by creating a separate array holding the references.

    Solution #0

    for (int i = Controls.Count - 1; i >= 0; i--)
    {
        Controls[i].Dispose();
    }
    

    Solution #1

    foreach (var control in Controls.Cast<Control>().ToArray())
    {
        control.Dispose();
    }