C# – How to set the back color of the row / column header cell in a datagridview – c# winform

ccolorsdatagridviewwinforms

I want to set the back color of the row header and column header intersection cell of a datagridview. I tried the below code, but it throws an exception that the number should be non negative.

DataGridViewCell cell = dgview.Rows[-1].Cells[-1];
cell.Style.BackColor = Color.Red;

I want to set the color as shown in the image below

enter image description here

I also refered the below article, but it shows how to set the color of the whole column header. But my requirement is to set the color of a single cell – row-column header intersection cell.

how-to-change-the-color-of-winform-datagridview-header

Any help is much appreciated. Thank you.

Regards,

Vinay

Best Answer

Store the current ColumnHeadersDefaultCellStyle in a variable.

Set the ColumnHeadersDefaultCellStyle to how you want the corner to be.

Then change all of the columns headers to how you want columns 0 to ... back to the old style.

Below is an example where the form is called "MyForm". This example shows the default constructor of MyForm.

Example:

    public MyForm()
    {
        InitializeComponent();

        // insert code here to add columns  ...
        // ...
        // ...
        // ...

        DataGridViewCellStyle oldDefault = dgview.ColumnHeadersDefaultCellStyle.Clone();

        dgview.ColumnHeadersDefaultCellStyle.BackColor = Color.Red;

        foreach (DataGridViewColumn item in dgview.Columns)
        {
            item.HeaderCell.Style = oldDefault;
        }
    }