2
Answers

Removing all buttons from form

Swatto

Swatto

9y
568
1
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)