user20493
user20493

Reputation: 5804

Change group box text color?

How do you change the text color of a group box in C#? The "documentation" doesn't even mention this, and Googling hasn't turned up an answer.

Thanks! Alan

Upvotes: 6

Views: 28962

Answers (5)

Mitja Bonca
Mitja Bonca

Reputation: 4546

Or I have changed your code a bit so user can choose between 2 types of color for groupBox only:

    private void SettingGroupBoxColor(bool bSelected)
    {
        if (!bSelected)
            groupBox1.ForeColor = Color.Red;
        else
            groupBox1.ForeColor = Color.Green;
        foreach (Control c in this.groupBox1.Controls)
        {
            c.ForeColor = Color.Black;
        }
    }

Passing "true" or "false" values to the upper mehod, will change the groupBox ForeColor only - while all other controls forecolor will remain default (black).

a cent of mine.

Upvotes: 2

nawfal
nawfal

Reputation: 73183

Actually all the answers posted here changes the forecolor of other controls like button, label etc residing inside the groupbox. To specifically change just the text colour of the groupbox there is a simple workaround.

    private void button1_Click(object sender, EventArgs e)
    {
        List<Color> lstColour = new List<Color>();
        foreach (Control c in groupBox1.Controls)
            lstColour.Add(c.ForeColor);

        groupBox1.ForeColor = Color.Red; //the colour you prefer for the text

        int index = 0;
        foreach (Control c in groupBox1.Controls)
        {
            c.ForeColor = lstColour[index];
            index++;
        }
    }

Of course the above code can be meaningless if you are adding controls programmatically later to the groupbox, but the good thing is you can handle all that situations by adding extra conditions in code. To be doubly sure, a list of keyvaluepair of control and forecolor can be employed.

Upvotes: 6

BFree
BFree

Reputation: 103740

If you're referring to the groupbox text itself, then use what Jon Skeet posted. If you're referring to all the subsequent controls in the groupbox, then you can use this code:

        foreach (Control c in this.groupBox1.Controls)
        {
            c.ForeColor = this.groupBox1.ForeColor; //or whatever color you want
        }

Upvotes: 4

Peter
Peter

Reputation: 1806

I'm assuming you are in winforms not in WPF now.

To change the text color of a group box you use ForeColor this changes the font colour in the header text.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500525

Use the ForeColor property. Sample code:

using System;
using System.Drawing;
using System.Windows.Forms;

class Test
{       
    [STAThread]
    static void Main(string[] args)
    {
        Form form = new Form();
        GroupBox group = new GroupBox();
        group.Text = "Text";
        group.ForeColor = Color.Red;
        form.Controls.Add(group);
        Application.Run(form);
    }
}

Upvotes: 13

Related Questions