I suppose the problem arises from messing up with the collection while trying to enumerate it.
I tested with the following and it seems to work:
while (Controls.Count > 0)
{
Controls.RemoveAt(0);
}
Here's the full code:
public class Form1 : Form
{
public Form1()
{
Random rand = new Random();
for (int i = 0; i < 30; i++)
{
Label lbl = new Label();
lbl.Text = i.ToString();
lbl.Location = new Point(rand.Next(10, 1000), rand.Next(10, 200));
Controls.Add(lbl);
}
this.MouseDoubleClick +=
new MouseEventHandler(Form1_MouseDoubleClick);
}
void Form1_MouseDoubleClick(object sender, MouseEventArgs e)
{
while (Controls.Count > 0)
{
Controls.RemoveAt(0);
}
}
}
I suggest you do the filtering in one go (copying the references to an array) and then run a foreach loop in the filtered controls calling Controls.Remove(C):
foreach (Control C in filteredControls)
{
Controls.Remove(C);
}