Search code examples
c#winformsbuttongroupbox

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


My goal is to disable all buttons (1 and 2) in groupbox1 (see the picture at the end). When I call the following Method DisableAllButtons(), only button 3 is disabled. What am i doing wrong?

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

Example WinForm


Solution

  • It's because you are using the Controls on your loop. So you are calling all the controls that is on your form which is the Button3and not the controls inside your GroupBox.

    To do that, you can do this.

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