我想根据条件在GridView中更改单元格的颜色。如果年龄小于70,则该单元格背景色将为Color.Pink
,否则为Color.Lime
。我在 Server中有一个表,其中有带有数据类型nvarchar(20)
的列Age
。这是我的密码:
Private Sub GridView1_RowCellStyle(sender As Object, e As RowCellStyleEventArgs) Handles GridView1.RowCellStyle
Try
If e.Column.FieldName = "Age" Then
If e.CellValue < 70 Then
e.Appearance.BackColor = Color.Pink
ElseIf e.CellValue = "" Then
e.Appearance.BackColor = Color.White
Else
e.Appearance.BackColor = Color.Lime
End If
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
End Sub
但是,每次读取列operator '<' is not defined for type 'dbnull' and type 'integer'
中没有值的行时,它都会给出错误的Age
。因此,我添加了ElseIf e.CellValue = "" Then
来检查是否存在没有值的行,但它仍然给出了相同的错误。我可以通过使用Try Catch
绕过错误,但我想解决这个问题,因为它可能会在未来带来问题。
截图:
发布于 2021-07-26 00:32:14
您可以安全地忽略空值(Nothing和DBNull.Value),如下所示:
Private Sub GridView1_RowCellStyle(sender As Object, e As RowCellStyleEventArgs) Handles GridView1.RowCellStyle
If e.CellValue Is Nothing OrElse e.CellValue Is DBNull.Value Then Return
'Try
If e.Column.FieldName = "Age" Then
If e.CellValue < 70 Then
e.Appearance.BackColor = Color.Pink
ElseIf e.CellValue = "" Then
e.Appearance.BackColor = Color.White
Else
e.Appearance.BackColor = Color.Lime
End If
'End If
'Catch ex As Exception
' MessageBox.Show(ex.ToString)
'End Try
End If
End Sub
https://stackoverflow.com/questions/68526608
复制