I have some controls that are built at run time. There is a groupbox with 3 radio buttons with the CheckedChanged event used to fill a control with a various number of groupboxes with each groupbox containing 4 more radio buttons. Since there is a various number of groupboxes inside this panel, I am trying to dispose of any groupbox that is currently in the panel, then I will rebuild with the ones I need to display. The problem is I am using a foreach loop to do so and for soem reason it only disposes of every other one. so if I were to have 8 groupboxes the 1st, 3rd, 5th and 7th would be disposed of but the 2nd,4th 6th and 8th would still show.

Here is the code I am using. I commented part of it out hoping to resolve the issue with no luck.

public void ClearRadios()
        {
            foreach (Control control in pnlDimensions.Controls)
            {
               // if (control.GetType() == typeof(GroupBox))
               // {
                    control.Dispose();
               // }
            }
        }

TIA for any help

foreach uses the IEnumerable interface to get it's list of objects. While using this interface, you can't add or delete elements of the collection or it causes issues with the internal tracking used by the interface. By calling Dispose on the control you've caused it to 'delete' itself without removing it from the collection (the Controls collection now has a reference to an object that doesn't exist).

If you want to remove all the controls, a for loop works better. If you need to remove only some controls, then you'll need a while loop:

public void ForLoop() {
    int n = pnlDimensions.Controls.Count;
    for (int i = 0; i < n; i++) {
        pnlDimensions.Controls.RemoveAt(0);
    }
}

public void WhileLoop() {
    int p = 0;
    while (p < pnlDimensions.Controls.Count) {
        if (pnlDimensions.Controls[p].GetType() == typeof(GroupBox)) {
            pnlDimensions.Controls.RemoveAt(p);
        } else {
            p++;
        }
    }
}

Thank You very much!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.