在winform datagrid C#中更改单元格背景颜色

时间:2012-10-02 08:10:17

标签: c# winforms datagrid

我希望在c#windows应用程序中根据值更改后台datagird单元格。例如,如果单元格值等于2单元格背景颜色变为红色,则单元格值为3单元格背景颜色设置为蓝色。

2 个答案:

答案 0 :(得分:5)

您可以使用CellFormatting事件:

private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 1)
        {
            if ((int)e.Value == 3)
                e.CellStyle.BackColor = Color.Blue;
            if ((int)e.Value == 2)
                e.CellStyle.BackColor = Color.Red;
        }
}

答案 1 :(得分:1)

你想要这样的东西

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    if (row.Cells[someColumnIndex].Value == 3)
        row.Cells[someColumnIndex].Style.BackColor = System.Drawing.Color.Blue;
    else if (row.Cells[someColumnIndex].Value == 2)
        row.Cells[someColumnIndex].Style.BackColor = System.Drawing.Color.Red;
}

我希望这会有所帮助。