如何根据判断数据的结果,改变DataGridView中对应记录的背景颜色?

有时候,我们希望DataGridView在加载数据时,能够根据表记录中某些数据的值,做一个判断,根据判断的结果,将对应的记录显示成不同的背景颜色,例如我们希望学生信息表中如果是男生,则将性别显示成红色背景,如下图:

image

这可以通过自定义DataGridView控件的CellFormatting事件,来实现,具体代码如下:

Private Sub DataGridView1_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    If (e.RowIndex >= 0 And e.ColumnIndex >= 0 And e.RowIndex < DataGridView1.Rows.Count - 1) Then
        If (DataGridView1.Columns(e.ColumnIndex).Name = "性别") Then
            Dim sex As String = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
            If Not IsDBNull(sex) Then
                If (sex.ToString() = "男") Then
                    e.CellStyle.BackColor = Color.Red
                End If
            End If
        End If
    End If
End Sub

注意因为DataGridView控件在显示数据时,会自动在表记录,末尾记录后天就一行空的记录,这时DataGridView1.Rows.Count等于表中实际记录个数+1,所以判断时,要防止DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value是空值,因此需要加上e.RowIndex < DataGridView1.Rows.Count - 1这个条件。当然了,也有其他的判断方法可以用。

转载于:https://www.cnblogs.com/ajiefj/archive/2010/04/05/1704530.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值