System.Web.UI.WebControls.DataGrid Bound Columns header coloring

Sushil Agarwal 406 Reputation points
2021-12-21T05:01:33.723+00:00

Hello eperts in an winform i am using ``System.Web.UI.WebControls.DataGrid grid1 = new System.Web.UI.WebControls.DataGrid();
grid1.HeaderStyle.Font.Bold = true;
grid1.DataSource = dgv1.DataSource;
grid1.DataMember = dgv1.DataSource.ToString();
grid1.DataBind();
grid1.Font.Name = "Verdana";
grid1.BorderStyle = System.Web.UI.WebControls.BorderStyle.Solid;
grid1.HeaderStyle.BackColor = Color.Blue;
grid1.HeaderStyle.ForeColor = Color.White;
grid1.HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
grid1.HeaderStyle.Wrap = false;
grid1.HeaderStyle.Font.Bold = true;
//for (int i = 0; i < grid1.Columns.Count; i++)
//{
// grid1.Columns[i].HeaderStyle.BackColor = Color.Yellow;
// grid1.Columns[i].HeaderStyle.ForeColor = Color.Black;
//}
// render the DataGrid control to a file
Cursor.Current = Cursors.WaitCursor;
using (StreamWriter sw = new StreamWriter(bindNavigator1.save2xlfile))
{
using (System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw))
{
grid1.RenderControl(hw);
}
}
how can i change color of some of columns, in above code the commented section of grid1.Columns.Count was always zero any no columns color could be set.
what is the right way to do it

Developer technologies ASP.NET Other
{count} votes

Accepted answer
  1. Lan Huang-MSFT 30,186 Reputation points Microsoft External Staff
    2021-12-22T02:40:15.017+00:00

    Hi @Sushil Agarwal ,
    You need to set the EnableHeadersVisualStyles flag of the datagridview to False, and set the background color through the ColumnHeaders DefaultCellStyle. BackColor property.
    If you do not set the EnableHeadersVisualStyles flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme.
    https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.enableheadersvisualstyles?redirectedfrom=MSDN&view=windowsdesktop-6.0#System_Windows_Forms_DataGridView_EnableHeadersVisualStyles

    dataGridView1.EnableHeadersVisualStyles = false;  
    dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;   
    dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Magenta;  
    dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Yellow;  
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.