我在datagridview中有3列,我们可以将其称为列0
,1
和2
,以及它的外观。
我的问题是,当列0
大于列2
时,如何让列1
变为橙色?例如,Banana Catsup 4 kg
列2
有5
,列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
答案 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