技术改变世界!学习改变自己!

每天进步一点点,遥不可及的事情,在你一点一滴的努力下,也会变成现实。

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

有时候,我们希望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这个条件。当然了,也有其他的判断方法可以用。

posted on 2010-04-05 09:41  阿捷  阅读(3030)  评论(0编辑  收藏  举报