Reputation: 217
I can't seem to return the background color of the current cell in my DatagridView. As an example lets say that the background Style.BackgroundColor color of all the cells in my grid are Color.Pink
Code:
private void grid_CellEnter(object sender, DataGridViewCellEventArgs e)
{
var cell = grid.CurrentCell;
var colour = cell.Style.BackColor;
}
This var colour is always black. What is wrong with my code.
Upvotes: 0
Views: 236
Reputation: 548
If you want to detect if the BackColor has been set or if you are looking at the DefaultCellStyle.BackColor you can use this to test:
Color CurrentBackColor = grid.Rows[r].DefaultCellStyle.BackColor;
if(!grid.Rows[r].Cells[c].Style.BackColor.IsEmpty)
CurrentBackColor = grid.Rows[r].Cells[c].Style.BackColor;
That should give you the actual BackColor you expect
Upvotes: 0
Reputation: 413
It depends on the method you used to set the background color. If you have used something like:
grid.Rows[r].DefaultCellStyle.BackColor = Color.Pink;
you can only get the color value from that DefaultCellStyle, and your cell.Style.BackColor will be empty and returns RGB(0,0,0) or black. So you need to change your code to:
var colour = grid.Rows[cell.RowIndex].DefaultCellStyle.BackColor;
or
var colour = grid.CurrentRow.DefaultCellStyle.BackColor;
But if for setting the colors you used something like:
grid.Rows[r].Cells[c].Style.BackColor = Color.Pink;
the cell.Style.BackColor has that Color.Pink value and your code works.
When you set the colors at design time by changing properties of the DataGridView, you need to use the first method to get the color value.
Upvotes: 1
Reputation: 3059
you can see the back color of selected cell like this
var color =dataGridName.DefaultCellStyle.SelectionBackColor;
Upvotes: 0