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
Control.Disposeis 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
Solution #1