在 VB.NET 中避免 DBNull?
Avoid DBNull in VB.NET?
我想根据条件更改 GridView 中单元格的颜色。如果年龄小于 70,则单元格背面颜色将为 Color.Pink
,否则为 Color.Lime
。我在 SQL Server 中有一个 table,它的列 Age
的数据类型为 nvarchar(20)
。这是我的代码:
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
它正在工作,但是每次它读取列 Age
中没有值的行时都会给我错误 operator '<' is not defined for type 'dbnull' and type 'integer'
。所以我添加了 ElseIf e.CellValue = "" Then
来检查是否有一行没有值,但它仍然给我同样的错误。我可以使用 Try Catch
绕过错误,但我想解决这个问题,因为它可能会在将来带来问题。
截图:
您可以放心地忽略空值(无和 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
我想根据条件更改 GridView 中单元格的颜色。如果年龄小于 70,则单元格背面颜色将为 Color.Pink
,否则为 Color.Lime
。我在 SQL Server 中有一个 table,它的列 Age
的数据类型为 nvarchar(20)
。这是我的代码:
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
它正在工作,但是每次它读取列 Age
中没有值的行时都会给我错误 operator '<' is not defined for type 'dbnull' and type 'integer'
。所以我添加了 ElseIf e.CellValue = "" Then
来检查是否有一行没有值,但它仍然给我同样的错误。我可以使用 Try Catch
绕过错误,但我想解决这个问题,因为它可能会在将来带来问题。
截图:
您可以放心地忽略空值(无和 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