Reputation: 311
I am dynamically adding some Controls to my Form and it works quite well but when I want to remove them again, it only removes a few of them in a weird (random) pattern (2 controls here, 2 there,...).
I tried using:
foreach (Control item in this.Controls.OfType<Control>())
{
if (item.Tag == "potentiallyRemove")
this.Controls.Remove(item);
}
And yes the controls I want to remove have all set the "Tag" Attribute.
I also tried to remove only the PictureBoxes:
foreach (Control item in this.Controls.OfType<PictureBox>())
{
this.Controls.Remove(item);
}
I don't want to use this.Controls.Clear()
because I have an heading line which i don't want to remove.
Is this a bug or something like that and if yes, is there any workaround?
Upvotes: 1
Views: 81
Reputation: 889
to avoid errors: Add the controls to an array and then remove them.
try this:
List<Control> controlsToBeRemoved = new List<Control>();
foreach (Control item in this.Controls.OfType<PictureBox>())
{
controlsToBeRemoved.Add(item);
}
foreach (Control item in controlsToBeRemoved)
{
this.Controls.Remove(item);
}
Upvotes: 1