foreach control c# skipping controls

2019-01-28 04:44发布

问题:

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();
    }
}

回答1:

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.



回答2:

Surprised that's not erroring on you, since you're modifying the collection as you're iterating over it. Use a for loop and start at the end:

for (int ii = Controls.Count - 1; ii >= 0; ii--)
{
    Control cntrl = Controls[ii];
    Controls.remove(cntrl);
    cntrl.Dispose();
}

(Starting at the end because otherwise you'd be changing the indexes of each control as you iterated.)



回答3:

Youre iterating over the same collection from whitch youre removing. Use this code:

    List<Control> cleanControls = new List<Control>();
    foreach(Control ctr in Controls)
    {
       if(cntrl.GetType() != typeof(Button))
       {
          cleanControls.Add(ctr);
       }
       else
       {
         ctr.Dispose();
       }
    } 
    Controls = cleanControls;

That's It! Hope I helped!