Noam650
Noam650

Reputation: 113

clear screen from buttons

Im trying to delete all the buttons in my WinForm.But somehow, it keeps few buttons in the form. How can I remove all the buttons in my form?What is the mistake at my code?!

void ClearScreen()
    {
        foreach (Control c in this.Controls)
        {
            if (c is Button)
                this.Controls.Remove(c);

        }


    }

Upvotes: 0

Views: 634

Answers (3)

chaliasos
chaliasos

Reputation: 9783

Try this:

void ClearScreen()
{
    List<Button> _buttons = this.Controls.OfType<Button>().ToList();

    foreach (var button in _buttons)
    {
        this.Controls.Remove(button);
    }
}

Upvotes: 2

doneyjm
doneyjm

Reputation: 145

foreach (Button btn in this.Controls.OfType<Button>())
            {
                this.Controls.Remove(bbb);
            }

this is a generic way to remove all the buttons from a form

Upvotes: 0

Emond
Emond

Reputation: 50672

The reason your code doesn't work is that you are modifying a collection while you are using the enumerator to loop through it.

Upvotes: 3

Related Questions