Changing Border Color of Group Boxes in Visual C#


Recently i came across this frustrating problem that i cant change the color of the border of the group box which was ruining my whole theme so i researched a lot about it and it was hard to find a good reliable solution as there were a lot of threads about it.Here is one i found working perfectly:

In the solution explorer right click on the project root file, go to add and click on class.



Name the class whatever you want and paste this code in the .cs file
 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Drawing;  
 using System.Data;  
 using System.Text;  
 {  
 using System.Windows.Forms;  
 namespace Sample2  
 private void GroupBoxTest_Load(object sender, EventArgs e)  
 public partial class GroupBoxTest : Form  
 {  
 {  
 myGroupBox.Text = "GroupBox1";  
 myGroupBox myGroupBox = new myGroupBox();  
 myGroupBox.BorderColor = Color.Red;  
 private Color borderColor;  
 this.Controls.Add(myGroupBox);  
 }  
 }  
 public class myGroupBox : GroupBox  
 {  
 public Color BorderColor  
 {  
 {  
 get { return this.borderColor; }  
 set { this.borderColor = value; }  
 }  
 public myGroupBox()  
 Size tSize = TextRenderer.MeasureText(this.Text, this.Font);  
 this.borderColor = Color.Black;  
 }  
 protected override void OnPaint(PaintEventArgs e)  
 {  
 Rectangle borderRect = e.ClipRectangle;  
 ControlPaint.DrawBorder(e.Graphics, borderRect, this.borderColor, ButtonBorderStyle.Solid);     
 borderRect.Y += tSize.Height / 2;  
 borderRect.Height -= tSize.Height / 2;  
 Rectangle textRect = e.ClipRectangle;  
 textRect.Width = tSize.Width;  
 textRect.X += 6;  
 }  
 textRect.Height = tSize.Height;  
 e.Graphics.FillRectangle(new SolidBrush(this.BackColor), textRect);  
 e.Graphics.DrawString(this.Text, this.Font, new SolidBrush(this.ForeColor), textRect);  
 }  
 }  


Actually what we did is we sub classed the "GroupBox" class as "myGroupBox".
After pasting the given code in the .cs file of the new class you added rebuild the project 



After a successful rebuild open the tool box and you will see a new GroupBox named as myGroupBox




Now place this GroupBox anywhere u want,go to its properties and under the miscellaneous section u will see a property "BorderColor".As u can see i changed the border color



Advertisement