0

I have a form containing two buttons.

The first one adds some GroupBoxes to the form, with this handler:

private void btnAdd_Click(object sender, EventArgs e)
{
    GroupBox[] g_arr = new GroupBox[2];
    for (int i = 0; i < g_arr.Length; i++)
    {
        g_arr[i] = new GroupBox();
        g_arr[i].Location = new Point(280, (i*-50) + 300);
        g_arr[i].Size = new Size(337, 380);

        this.Controls.Add(g_arr[i]);
            }
        }

The second one is supposed to remove every GroupBoxes inside the form, but not all of them disappear when it's clicked:

private void btnDelete_Click(object sender, EventArgs e)
{
    foreach (Control c in this.Controls)
    {
        if (c is GroupBox)
        {
            this.Controls.Remove(c);
        }                    
    }
}

Why doesn't my remove button manage to remove every GroupBox?

Kilazur
  • 3,089
  • 1
  • 22
  • 48
akoxi
  • 225
  • 1
  • 3
  • 10
  • the iterating collection of `foreach` is read-only. It is surprising that an exception is not thrown. – mcy Feb 04 '15 at 15:07

1 Answers1

4

Don't modify the collection while you are iterating. You can use OfType method to get all GroupBoxes and ToList to copy them into a list so you can iterate over it instead of the original collection:

foreach (Control c in this.Controls.OfType<GroupBox>().ToList())
{
     this.Controls.Remove(c);
} 

This will only remove the GroupBox controls that are direct child of the Form.If you have nested controls then you need a recursive search like in this answer.

Community
  • 1
  • 1
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • Thank you sir/mam. Actually I tried the `OfType` method first but I don't know about `ToList`:) – akoxi Feb 04 '15 at 15:11