Search code examples
vb.netdatagridviewbackcolor

Can't get DataGridView cell BackColor property


I'm trying to retrieve the current color of a DataGridView cell while iterating through the Grid. I am explicitly setting the BackColor for both RowsDefaultCellStyle and AlternatingRowsDefaultCellStyle in the Form Load event.

I'm trying to get the cell BackColor per this question, however, at run time, while iterating through cells in a row, in the Immediate Window this: ?dgvemployees.Rows(rowIndex).Cells(i + 1).Style.BackColor.ToString returns "Color [Empty]" every time - even if I change the indexes to get another cell that I know has the default color set.

Am I missing something or not doing something right?


Solution

  • This page on the Cell Style says:

    The DataGridView control displays its cells using the styles indicated by the cell InheritedStyle property, which inherits styles from other properties of type DataGridViewCellStyle. The styles specified through the Style property override the styles specified through all other cell-style properties, but do not necessarily indicate all the styles that contribute to the cell's appearance.

    Basically, you are trying to access the specific cell back color when it hasn't been set. Even though you have set the back color of the rows, it can be overridden at the cell level.

    Thankfully, Microsoft has given us a nice way to find the inherited style of the cell, which will get you the grid-level setting for these cells (unless something further down the chain has overridden that).

    ?dgvemployees.Rows(1).Cells(2).InheritedStyle.BackColor.ToString()
    

    If I had something else that could override this value and cause problems, then I think I'd be left doing a modulus on the row count to see if it was an alternating row or not.