Search code examples
sql-servervb.netdevexpress

Avoid DBNull in VB.NET?


I want to change the color of the cell in GridView based on the condition. If age is less than 70 then the cell back color will be Color.Pink otherwise Color.Lime. I have a table in SQL Server and it has column Age in it with data type nvarchar(20). Here's my code:

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

It's working however it gives me the error operator '<' is not defined for type 'dbnull' and type 'integer' every time it reads a row with no value in column Age. So I added ElseIf e.CellValue = "" Then to check if there's a row with no value but it still gives me the same error. I can bypass the error by using Try Catch but I want to resolve this issue as it may bring problems in the future.

Screenshot:

error message


Solution

  • You can safely ignore the empty (Nothing and DBNull.Value) values something like this:

    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