[c#] DataGridView changing cell background color

I have the following code :

private void dgvStatus_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    foreach (DataGridViewRow row in dgvStatus.Rows)
    {
        row.Cells[color.Index].Style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
    }
}

I am trying to set the background color of each cell from the background color column. this doesn't work the color never change. Any idea of why?

I've been looking around but didn't found anything usefull

This question is related to c# winforms datagridview

The answer is


Simply create a new DataGridViewCellStyle object, set its back color and then assign the cell's style to it:

    DataGridViewCellStyle style = new DataGridViewCellStyle();
    style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor);
    style.ForeColor = Color.Black;
    row.Cells[color.Index].Style = style;

protected void grdDataListeDetay_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[3].Text != "0")
        {
            for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
            {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;
            }
        }
    }
}

dataGridView1[row, col].Style.BackColor = System.Drawing.Color.Red;

If you are still intrested in why this didn't work for you at first:

The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.

Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.

To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).


dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.LightGreen;

try the following (in RowDataBound method of GridView):

protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // this will only change the rows backgound not the column header 

    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col
        e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col
    }
}

Similar as shown and mentioned:

Notes: Take into consideration that Cells will change their color (only) after the DataGridView Control is Visible. Therefore one practical solution would be using the:

VisibleChanged Event

In case you wish to keep your style when creating new Rows; also subscribe the:

RowsAdded Event


Example bellow:

///<summary> Instantiate the DataGridView Control. </summary>
private DataGridView dgView = new DataGridView;

///<summary> Method to configure DataGridView Control. </summary>
private void DataGridView_Configuration()
{
    // In this case the method just contains the VisibleChanged event subscription.

    dgView.VisibleChanged += DgView_VisibleChanged;

    // Uncomment line bellow in case you want to keep the style when creating new rows.
    // dgView.RowsAdded += DgView_RowsAdded;
}

///<summary> The actual Method that will re-design (Paint) DataGridView Cells. </summary>
 private void DataGridView_PaintCells()
 {
     int nrRows = dgView.Rows.Count;
     int nrColumns = dgView.Columns.Count;
     Color green = Color.LimeGreen;

     // Iterate over the total number of Rows
     for (int row = 0; row < nrRows; row++)
     {
         // Iterate over the total number of Columns
         for (int col = 0; col < nrColumns; col++) 
         {
             // Paint cell location (column, row)
             dgView[col, row].Style.BackColor = green;
         }
     }
 }

///<summary> The DataGridView VisibleChanged Event. </summary>
private void DataGridView_VisibleChanged(object sender, EventArgs e)
{
    DataGridView_PaintCells();
}

/// <summary> Occurrs when a new Row is Created. </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
{ 
    DataGridView_PaintCells(); 
}


Finally: Just call the DataGridView_Configuration() (method)
i.e: Form Load Event.


int rowscount = dataGridView1.Rows.Count;         

for (int i = 0; i < rowscount; i++)
{            
    if (!(dataGridView1.Rows[i].Cells[8].Value == null))
    {
        dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow;
    }
}

You can use the VisibleChanged event handler.

private void DataGridView1_VisibleChanged(object sender, System.EventArgs e)
{
    var grid = sender as DataGridView;
    grid.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to datagridview

How to refresh or show immediately in datagridview after inserting? Delete a row in DataGridView Control in VB.NET Looping each row in datagridview How to get cell value from DataGridView in VB.Net? Changing datagridview cell color based on condition Index was out of range. Must be non-negative and less than the size of the collection parameter name:index how to bind datatable to datagridview in c# DataGridView AutoFit and Fill How to export dataGridView data Instantly to Excel on button click? Populate a datagridview with sql query results