Search code examples
c#datagridviewcell-formatting

Issue with CellFormatting of a DataGridView


I have a DataGridView that is populated with data pulled from several tables (I'm using SQLite but I don't think that's relevant here). One of the columns (11) may have a value or may be empty. I want to colour the row green if there is a value and do nothing if there isn't. I have this code in CellFormatting to do this:

private void dgv_CellFormatting(Object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 11)
    {
        if (!String.IsNullOrEmpty(dgv.Rows[e.RowIndex].Cells[11].Value.ToString()))
        {
            dgv.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Green;
        }
    }
}

This works perfectly if there's no value in column 11 in the first row, but if there is then the entire DataGridView is coloured in green regardless of whether or not there is a value in column 11.

Thanks in advance for any assistance.


Solution

  • I will assume that is what you want is that “IF” the value of the cell in column 11 is NOT empty, then color that row green, AND if the value of the cell in column 11 IS empty, then do not color it green.

    The problem (I see) in the posted code is that the back color is NEVER getting set back to white if the value in cell 11 IS empty.

    Example, using the posted code, let us say that row 0 has a value in column 11 and it is NOT empty! Given this, the Cell_Formatting event will obligingly color row 0 green. Now, with row 0 colored green, let us click into the cell on row 0 cell 11 and “REMOVE” the data in the cell 11 to make it empty. After removing the data in cell 11, the Cell_Formatting event will fire. Since the value in cell 11 IS empty, the row will NOT be colored green.

    Unfortunately, the row is ALREADY green.

    This mean that whenever a row gets turned green… IT WILL ALWAYS REMAIN GREEN, regardless of the value in cell 11.

    Below is the code that will change the row color to green IF the value in cell 11 is NOT empty and will color the row white, when the value in cell 11 IS empty.

    private void dgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) {
      if (e.ColumnIndex == 11) {
        if (!String.IsNullOrEmpty(dgv.Rows[e.RowIndex].Cells[11].Value.ToString())) {
          dgv.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Green;
        }
        else {
          dgv.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
        }
      }
    }
    

    I hope that makes sense.