I had exactly the problem indicated in the question, so this might help someone. I tried to clear the control collection before overwriting it.
private void clearCollection(Control.ControlCollection target) { foreach (Control Actrl in target) { if (Actrl is Label || Actrl is Button) { target.Remove(Actrl); } } }
Having deleted the control inside the foreach loop, it should fiddle with internal pointers, and the result is that the controls in the collection are skipped. My solution was to find all the controls and then delete in a separate loop.
private void clearCollection(Control.ControlCollection target) { List<Control> accumulator = new List<Control>(); foreach (Control Actrl in target) { if (Actrl is Label || Actrl is Button) { accumulator.Add(Actrl);
source share