Paul Edward Pagente Paul Edward Pagente - 1 month ago 8
Vb.net Question

Greater Than and Less Than in Column in Datagridview VB.Net

I have 3 columns in datagridview lets call it column

0
,
1
and
2
and here what it looks like.

enter image description here

My question is how can I make the column
0
turn to color orange when column
2
is greater than column
1
? For example the
Banana Catsup 4 kg
column
2
has a
5
and column
1
is greater than column
2
so in that case the column 0 will not turn to orange but in my example it turns to orange. Here is my code

Try
For i As Integer = DataGridView1.RowCount - 1 To 3 Step -1
If DataGridView1.Rows(i).Cells(1).Value > DataGridView1.Rows(i).Cells(2).Value Then
Me.DataGridView1.Rows(i).Cells(1).Style.BackColor = Color.Orange
End If
Next
Catch
End Try


When i observe my code it seems that my code works only on the first number. Please help me

TYSM

Answer

Why complicate things when you can just do it like this?

    Try
        For i = 0 To DataGridView1.RowCount - 1
            If Val(DataGridView1.Rows(i).Cells(1).Value.ToString) > Val(DataGridView1.Rows(i).Cells(2).Value.ToString) Then
                Me.DataGridView1.Rows(i).Cells(0).Style.BackColor = Color.Orange
            End If
        Next
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try

Also, having an empty catch will give you trouble sooner or later.

Added Val() to cells to make sure it won't cause any problem when it's blank.