Removing dynamically added controls from WinForm

.net, c#, winforms

Solution

The easiest way to remove all controls from a controls collection is to call its `Clear` method:

salesBox.Controls.Clear();

Modifying collections can invalidate enumerators and yield unpredictable results or even throw an `InvalidOperationException`, depending on the collection type (see the "Remarks" section in IEnumerable.GetEnumerator Method on MSDN). Since `foreach` uses an enumerator you should not alter the collection it is iterating.

Use a `for` statement, if you have to delete selectively and also iterate backwards, in order not to get wrong index values after removing items:

for (int i = salesBox.Controls.Count - 1; i >= 0; i--) {
    Control c = salesBox.Controls[i];
    if (c is TextEdit || c is Label) {
        salesBox.Controls.RemoveAt(i);
    }
}

Problem

I have a GroupBox in which I dynamically add controls into it. The controls I add are of two types `DevExpress.XtraEditors.TextEdit` and `Windows.Forms.Label` I am trying to remove these controls using the following ``` foreach (Control control in salesBox.Controls) { control.Dispose(); salesBox.Controls.Remove(control); } ``` This is correctly removing the `TextEdit` controls but not the `Label` controls. The loop is not iterating through the `Label` controls.

Original source