Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foreach control c# skipping controls

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();
    }
}
like image 551
Altimus Prime Avatar asked Jul 13 '13 04:07

Altimus Prime


1 Answers

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.

like image 78
McGarnagle Avatar answered Sep 19 '22 00:09

McGarnagle