Reputation: 5982
In windows application, I'm using a datagridview. Is that possible to highlight color for some of the cells... That is, Some cells should be highlighted. How can I accomplish this?
Upvotes: 1
Views: 11243
Reputation: 2194
If you just want to change the current selected cell.
private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
grid1.CurrentCell.Style.SelectionBackColor = Color.Red;
}
Upvotes: 0
Reputation: 5944
In the CellFormatting
event of the grid you can check the values, which are going to be displayed, and change the CellStyle
accordingly.
You can use the RowIndex
and ColumnIndex
properties of the event arguments, to check which cell is going to be displayed. And you can set the CellStyle
property, when it needs to be changed (for example e.CellStyle.ForeColor = Color.Red;
).
Upvotes: 2
Reputation: 1739
Setting the defaultcellstyle will color the entire row. Setting a default value for a single row just sounds like a bad idea. You would need an else statement for all those rows that dont go under the defaultcellstyle set for "someVal" not to have them colored like the rest because they dont take any action. Plus, typecasting to the actual type of Value should give you better performance than ToString(). I can imagine this will probably be looped over the entire list for every update.
Instead, for just coloring a single cell, do it like this:
foreach (DataGridViewRow row in dataGridView.Rows)
{
if ((string)row.Cells[0].Value == "someVal")
{
row.Cells[0].Style.BackColor= Color.Tomato;
}
}
Upvotes: 0
Reputation: 50752
foreach (DataGridViewRow row in dataGridView.Rows)
{
if (row.Cells[0].Value.ToString() == "someVal")
{
row.DefaultCellStyle.BackColor = Color.Tomato;
}
}
Upvotes: 2