Tutorial :Change group box text color?



Question:

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


Solution:1

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);      }  }  


Solution:2

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          }  


Solution:3

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.


Solution:4

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.


Solution:5

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.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »