The issue you're running into is that you're altering the collection that you're enumerating, instead try something like this:
Code:
private void btnAddControls_Click(object sender, System.EventArgs e)
{
int count = new Random(DateTime.Now.TimeOfDay.Seconds).Next(49) + 1;
this.pnlContainer.SuspendLayout();
for( int i=0; i<count; i++ )
{
myControl control = new myControl();
control.Name = "myControl" + i.ToString();
control.Location = new Point((i % 4) * control.Width, (i / 4) * control.Height);
this.pnlContainer.Controls.Add(control);
}
this.pnlContainer.ResumeLayout();
}
private void btnClearControls_Click(object sender, System.EventArgs e)
{
this.pnlContainer.SuspendLayout();
for( int i=0; i<this.pnlContainer.Controls.Count; i++ )
if( this.pnlContainer.Controls[i] is myControl )
{
myControl control = (myControl)this.pnlContainer.Controls[i];
this.pnlContainer.Controls.RemoveAt(i);
control.Dispose();
i--;
}
this.pnlContainer.ResumeLayout();
}