How to color some specific values on DataGridView in

Hakan used Ask the Experts™
Hello I'm using below code to color True, False and NaN(not Applicable) strings to check what's wrong or OK.

My code works but it seems it's not logic approach to do that. If you have any experience i'd be grateful.

        Private Shared Sub ColorCells(ByVal dgv As DataGridView)
            If dgv.Rows.Count > 0 Then
                For i = 0 To dgv.Rows.Count - 1
                    For j = 0 To dgv.ColumnCount - 1
                        Select Case dgv.Rows(i).Cells(j).Value.ToString
                            Case "True"
                                dgv.Rows(i).Cells(j).Style.BackColor = Color.Green
                            Case "False"
                                dgv.Rows(i).Cells(j).Style.BackColor = Color.Red
                                dgv.Rows(i).Cells(0).Style.BackColor = Color.Red
                            Case "NaN"
                                dgv.Rows(i).Cells(j).Style.BackColor = Color.Orange
                            Case Else
                        End Select
            End If
        End Sub

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Éric MoreauSenior .Net Consultant
Top Expert 2016

why isn't it logical?  if you 3 values, you cannot just do a boolean comparison


It's a bit cascaded with if else for each and switch structures and i thought there were more logic structures experienced users do
Senior .Net Consultant
Top Expert 2016
you could reverse the first if:
If dgv.Rows.Count = 0 Then return

Open in new window

that would eliminate one level. but the other levels are required.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial