Search code examples
c#winformsgroupbox

How can I change the font color in a groupbox when I disable the groupbox


I am using a Groupbox in c# and at first, it is Enabled.

when I use Groupbox1.Enabled = false, it's fore color (and everythings' forecolor which is in it) change to default black. and even the command label1.Forecolor = Color.White does not work. (Which label1 is in the Groupbox1). when I Enable Groupbox, it fixes. But I want it to be White whether Groupbox1 is enabled or disabled.


Solution

  • Alternatively, you could simply not disable the GroupBox. Instead, create a method that disables all of it's children;

    private void DisableChildren(Control control)
    {
        foreach(var child in control.Controls.Cast<Control>().Where(child.GetType != typeof(Label) && child.GetType() != typeof(GroupBox)))
        {
            if(child.HasChildren)
            {
                DisableChildren(child);
            }
            child.Enabled = false;
        }
    }
    

    You can see I'm not disabling Labels or nested GroupBoxes.

    Just use like this where you would normally disable the GroupBox;

    DisableChildren(GroupBox1);
    

    Just as a side note: The same thing happens with any container under Windows Forms (GroupBox, Panel, etc).