开发者

Highlight Color for particular cells in DataGridView

In windows application, I'm using a datagridview. Is that possible to highlight color for some of th开发者_如何学Pythone cells... That is, Some cells should be highlighted. How can I accomplish this?


foreach (DataGridViewRow row in dataGridView.Rows)
{
    if (row.Cells[0].Value.ToString() == "someVal")
    {
        row.DefaultCellStyle.BackColor = Color.Tomato;
    }
}


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;).


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;
    }
}


If you just want to change the current selected cell.

private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {

        grid1.CurrentCell.Style.SelectionBackColor = Color.Red;


    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜