0

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

Dale K
  • 25,246
  • 15
  • 42
  • 71
  • Take a look at this answer [here](https://stackoverflow.com/questions/222834/handling-dbnull-data-in-vb-net) that has a similiar problem, something along the lines of ```If NOT IsDbNull(e.CellValue) Then ...``` – Otter Jul 26 '21 at 08:29

1 Answers1

1

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
Mikhail
  • 9,186
  • 4
  • 33
  • 49