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

1
  • Take a look at this answer here that has a similiar problem, something along the lines of If NOT IsDbNull(e.CellValue) Then ... Commented Jul 26, 2021 at 8:29

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.