发布
社区首页 >问答首页 >避免DBNull在VB.NET?

避免DBNull在VB.NET?
EN

Stack Overflow用户
提问于 2021-07-26 08:22:05
回答 1查看 237关注 0票数 0

我想根据条件在GridView中更改单元格的颜色。如果年龄小于70,则该单元格背景色将为Color.Pink,否则为Color.Lime。我在 Server中有一个表,其中有带有数据类型nvarchar(20)的列Age。这是我的密码:

代码语言:javascript
代码运行次数:0
复制
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绕过错误,但我想解决这个问题,因为它可能会在未来带来问题。

截图:

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-26 08:32:14

您可以安全地忽略空值(Nothing和DBNull.Value),如下所示:

代码语言:javascript
代码运行次数:0
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68526608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档