Dhanapal
Dhanapal

Reputation: 14507

How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?

I need to change the group box text to a specific color without changing the color of what is inside the group box.

The following code sets the ForeColor of the GroupBox to pink but this settings cascades to all the child controls as well:

groupbox.ForeColor = Color.Pink 

How do I change the ForeColor of a GroupBox without having that color applied to every child control as well?

Upvotes: 4

Views: 4795

Answers (2)

parfilko
parfilko

Reputation: 1454

form_load()
{
    ...
    foreach (Control ctl in groupbox.Controls) 
    {
        // load color value from parent and explicitly set it to control level
        ctl.ForeColor = ctl.ForeColor;
    }
    ...
}


some_click()
{
    groupbox.ForeColor = Color.Pink;
}

someother_click()
{
    groupbox.ForeColor = Color.Green; 
}

Color is not set for childcontrol until it done explicitly, and when childcontrol color requested it taken from the parent. Changing parent's color will refresh all it's content and childcontrol will take color from the parent.

If you set (explicitly) child color then child will not "asking" parent.

Child color can be set in designer too, but if color is the same as parent's color, designer will reduce this setting. Code in load event force child to have own color.

Upvotes: 0

Patrick McDonald
Patrick McDonald

Reputation: 65411

You could iterate through all the controls in the GroupBox and set their respective ForeColor properties:

groupBox1.ForeColor = Color.Pink;
foreach (Control ctl in groupBox1.Controls) {
    ctl.ForeColor = SystemColors.ControlText;
}

Upvotes: 4

Related Questions