与其他字段进行比较时,gridview上的背景颜色发生变化
问题描述:
我有一个DataGridView,但是我必须将两个字段彼此比较
,但是当一个字段大于另一个字段时,该字段必须更改为某种颜色,该如何在C#中编写此方法:
I have a DataGridView, but I have to compare two fields to one another but when the one field is greater than the other the field has to change to a certain color, how can I write this method in C#:
答
这是一个简单的示例:
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;
}