例1:在dataGridView中根据不同的数据显示不同的背景色便于区分数据,方便区分和查看。基本方法就是遍历所有行,根据字段的区只要求,设置背景颜色。代码如下
private void dvgConsolidation_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//根据列表中数据不同,显示不同颜色背景
foreach( DataGridViewRow dgRow in DGVAllRentList.Rows ){
//判断
if ((double)(dgRow.Cells[5].Value) < 0.2 || (double)(dgRow.Cells[5].Value) > 0.8)
{
//将这行的背景色设置成红色
dgRow.DefaultCellStyle.BackColor = Color.Red;
}
}
}
例2:根据当天日期,将当天日期以前的数据行,变成红色。
//设置DataGridView事件(绘制单元格是发生)
private void dvgConsolidation_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
//循环遍历DataGridView的行
foreach (DataGridViewRow dgRow in dvgConsolidation.Rows)
{
//判断循环遍历DataGridView第九列的时间是否小于当前时间
if ((DateTime)(dgRow.Cells[8].Value) < DateTime.Today)
{
//将这行的背景色设置成红色
dgRow.DefaultCellStyle.BackColor = Color.Red;
}
}
}