从按钮清除屏幕

时间:2012-05-28 09:33:35

标签: c# winforms button

我试图删除WinForm中的所有按钮。但不知何故,它在表单中保留了几个按钮。 如何删除表单中的所有按钮?我的代码有什么错误?!

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

        }


    }

3 个答案:

答案 0 :(得分:3)

您的代码不起作用的原因是您在使用枚举器循环时修改集合。

答案 1 :(得分:2)

试试这个:

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

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

答案 2 :(得分:0)

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

这是从表单中删除所有按钮的通用方法