Datagridview VB.Net中的大于和小于列

时间:2016-10-18 07:00:59

标签: vb.net datagridview

我在datagridview中有3列,我们可以将其称为列012,以及它的外观。

enter image description here

我的问题是,当列0大于列2时,如何让列1变为橙色?例如,Banana Catsup 4 kg25,列1大于列2,所以在这种情况下,第0列不会变成橙色但是在我的例子中,它变成了橙色。这是我的代码

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

当我观察我的代码时,似乎我的代码仅适用于第一个数字。请帮帮我

TYSM

2 个答案:

答案 0 :(得分:0)

为什么这样做会让事情变得复杂?

    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

此外,空catch迟早会给你带来麻烦。

在单元格中添加了Val(),以确保在单元格空白时不会导致任何问题。

答案 1 :(得分:0)

您正在比较两个字符串值。首先需要将col1和col2值转换为INT然后进行比较。

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