DataGridView CellFormatting不格式化所有指定的单元格

时间:2014-06-11 19:10:26

标签: vb.net winforms datagridview

我有一个SQL查询,通过DataTable填充DataGridView:

SELECT top 100 a.Ordnum, oldBFE, newBFE, oldCBRA, newCBRA, oldLOMC, newLOMC, oldfld,    newfld FROM 
(SELECT Ordnum, PrpBFE as oldBFE, CBRADte as oldCBRA, LOMCDte as oldLOMC, FldZne AS oldfld 
FROM [TOD].[dbo].[Orders] with (NOLOCK) WHERE RecRevDesc = '1 - Order Clone') a 
JOIN 
(SELECT Ordnum, PrpBFE as newBFE CBRADte as newCBRA, LOMCDte as newLOMC, FldZne AS newfld 
FROM [TOD].[dbo].[Orders] with (NOLOCK) WHERE RecRevDesc = '2 Determination Completed-Workflow') b 
ON a.Ordnum = b.Ordnum

如果某些细胞对的值不相等,我需要两个细胞都有一个红色的前色。现在,我通过cellformatting事件解决了这个问题:

For i As Integer = 0 To Me.gridCompare.RowCount - 1
  If Me.gridCompare.Rows(i).Cells(1).ToString <> Me.gridCompare.Rows(i).Cells(2).ToString Then
    Me.gridCompare.Rows(i).Cells(1).Style.ForeColor = Color.Red
    Me.gridCompare.Rows(i).Cells(2).Style.ForeColor = Color.Red
  ElseIf Me.gridCompare.Rows(i).Cells(3).ToString <> Me.gridCompare.Rows(i).Cells(4).ToString Then
    Me.gridCompare.Rows(i).Cells(3).Style.ForeColor = Color.Red
    Me.gridCompare.Rows(i).Cells(4).Style.ForeColor = Color.Red
  ElseIf Me.gridCompare.Rows(i).Cells(5).ToString <> Me.gridCompare.Rows(i).Cells(6).ToString Then
    Me.gridCompare.Rows(i).Cells(5).Style.ForeColor = Color.Red
    Me.gridCompare.Rows(i).Cells(6).Style.ForeColor = Color.Red
  ElseIf Me.gridCompare.Rows(i).Cells(7).ToString <> Me.gridCompare.Rows(i).Cells(8).ToString Then
    Me.gridCompare.Rows(i).Cells(7).Style.ForeColor = Color.Red
    Me.gridCompare.Rows(i).Cells(8).Style.ForeColor = Color.Red
  End If
Next

但是,只有单元格1和2具有正确的格式。我究竟做错了什么?列的顺序无关紧要。我也尝试了个别的IF语句。

1 个答案:

答案 0 :(得分:1)

您不能使用ElseIf分支,因为这会阻止测试其他对。将每个测试放在自己的IF-EndIf中。您还需要测试Cell的Value属性:

If Me.gridCompare.Rows(i).Cells(1).Value.ToString <> _
   Me.gridCompare.Rows(i).Cells(2).Value.ToString Then
  'etc
End If

If Me.gridCompare.Rows(i).Cells(3).Value.ToString <> _
   Me.gridCompare.Rows(i).Cells(4).Value.ToString Then
  'etc
End If

此外,确保这些单元格不为空(或什么都不是),否则会引发异常。