Swatto

Swatto

  • NA
  • 23
  • 11k

Removing all buttons from form

Jan 31 2015 9:49 AM
Hello all,

Why did one method work but the other did not and produce weird results?

I was trying to remove all controls of type button from a form.  I tried two methods:

This worked:

       public void ClearButtons()
        {
            for (int i = 0; i < this.Controls.Count; i++)
            {
                if (Controls[i] is Button)
                {
                    Controls.RemoveAt(i);
                    i--;
                }
            }
        }


Didn't work (I got weird results, some buttons would stay on the form):


  foreach(Control control in Controls)
                    {
                        if (control is Button)
                            Controls.Remove(control);
                    }

Answers (2)