I have a DataGridView
bound to a DataSet
. Two of the columns in the DataGridView
are status columns (MatchStatus, EscalationStatus), which change fore and back color depending on the content of the cells in those columns. When the user selects a row, the entire row changes to white text on blue background. This is fine, but I want the two status columns to retain their custom colours. Currently I'm doing this in the CellFormatting
event.
Setting up the grid:
grid.AllowUserToAddRows = false;
grid.AllowUserToDeleteRows = false;
grid.AllowUserToOrderColumns = false;
grid.AutoGenerateColumns = false;
grid.ReadOnly = true;
grid.MultiSelect = false;
grid.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
grid.CellBorderStyle = DataGridViewCellBorderStyle.SingleVertical;
grid.Columns.Clear();
... load data ...
grid.DataSource = _somedata;
grid.Refresh();
CellFormatting event:
private void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if ((grid.Columns[e.ColumnIndex].DataPropertyName == "MatchStatus") ||
(grid.Columns[e.ColumnIndex].DataPropertyName == "EscalationStatus"))
{
switch (grid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().ToUpper())
{
case "UNTESTED":
e.CellStyle.ForeColor = Color.White;
e.CellStyle.BackColor = Color.Gray;
break;
case "CCR EXPIRED":
case "GBR EXPIRED":
case "LIMIT MISMATCH":
case "EXPIRY MISMATCH":
e.CellStyle.ForeColor = Color.Black;
e.CellStyle.BackColor = Color.Orange;
break;
case "LIMIT EXPIRED":
case "LIMIT EXCEEDED":
e.CellStyle.ForeColor = Color.Red;
e.CellStyle.BackColor = Color.White;
break;
default:
e.CellStyle.ForeColor = Color.Black;
e.CellStyle.BackColor = Color.White;
break;
}
}
}
How do I retain the formatting of just those two columns when the row is selected?
As indicated in the comment above by @dr.null (all credit to them), the answer is:
"Set the same color for e.CellStyle.BackColor and e.CellStyle.SelectionBackColor. Do the same for the foreground colors."