WinForms 和 C#:如何禁用组框中的按钮?

WinForms and C#: How to disable buttons in a groupbox?

我的目标是禁用 groupbox1 中的所有按钮(1 和 2)(见最后的图片)。当我调用以下方法 DisableAllButtons() 时,只有按钮 3 被禁用。我做错了什么?

    private void DisableAllButtons()
    {
        try
        {
            foreach (Control c in Controls)
            {
                Button button = (Button)c;
                button.Enabled = false;
            }
        }
        catch
        {
        }
    }

这是因为您在循环中使用了 Controls。因此,您正在调用表单上的所有控件,即 Button3 而不是 GroupBox 中的控件。

要做到这一点,你可以这样做。

public void DisableButton()
{
        List<Button> btn = groupBox1.Controls.OfType<Button>().ToList();
        foreach (var b in btn)
        {
            b.Enabled = false;
        }
}