背景当与彼此的字段进行比较时,网格视图上的颜色更改

时间:2017-09-21 06:57:00

标签: c# datagridview

我有一个DataGridView,但我必须将两个字段相互比较 但当一个字段大于另一个字段时,字段必须更改为某种颜色,如何在C#中编写此方法:

enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个简单的例子:

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    DataGridView dgv = dataGridView1;
    if (e.ColumnIndex < 0 || e.RowIndex < 0) return;
    if (dgv[0, e.RowIndex].Value == null ||dgv[1, e.RowIndex].Value == null) return;
    // assuming integers, adapt to real types and real column indices!
    dgv[1, e.RowIndex].Style.BackColor = 
                            (int)dgv[0, e.RowIndex].Value < (int)dgv[1, e.RowIndex].Value ?
                                        Color.LightSalmon : dgv.DefaultCellStyle.BackColor;
}