foreach control c# skipping controls
c#, controls, enumeration, foreach, winforms
Solution
I think this way is a bit more readable:
var controlsToRemove = Controls.OfType<Button>().ToArray();
foreach (var control in controlsToRemove)
{
Controls.Remove(control);
cntrl.Dispose();
}
Calling `ToArray()` makes a new concrete collection, so that you can enumerate over one and modify the other.
Problem
I have the following loop to remove the buttons in my C# Windows Forms application. The only problem is that it skips every other button. How do I go about removing all the button controls from my form? ``` foreach (Control cntrl in Controls) { if(cntrl.GetType() == typeof(Button)) { Controls.Remove(cntrl); cntrl.Dispose(); } } ```