一种经济的方法是使用CellFormatting 事件。这将在该单元格第一次显示时触发。它只会针对可见行触发,因此应该更快。
Then I loop through the grid view to do something like update the data of all colored rows
如果数据来自 db(OP 提到了查询),您应该像数据源一样对数据进行操作。 DGV 只是用户对数据的看法。与其作用于某种颜色的行,不如作用于零件编号或决定颜色的任何东西。您还可以使用此或那个零件号创建记录视图,并对其进行操作/循环以简化流程。
由于数据可以更改,您需要处理 2 个事件:CellFormatting 和 CellValueChanged
Private Sub dgv1_CellFormatting(...) Handles dgv1.CellFormatting
' default start up color
If e.ColumnIndex = 3 Then
e.FormattingApplied = ColorMyRow(e.RowIndex, e.ColumnIndex)
Else
e.FormattingApplied = False
End If
End Sub
Private Sub dgv1_CellValueChanged(...) Handles dgv1.CellValueChanged
' if the target cell changes, update
If e.ColumnIndex = 3 Then
ColorMyRow(e.ColumnIndex, e.RowIndex)
End If
End Sub
' DRY
Private Function ColorMyRow(rowIndex As Int32, colIndex As Int32) As Boolean
Dim bass As Color = Color.PeachPuff
Dim pike As Color = Color.SeaShell
Dim salmon As Color = Color.Salmon
Select Case dgv1.Rows(rowIndex).Cells(colIndex).Value.ToString
Case "Bass"
dgv1.Rows(rowIndex).DefaultCellStyle.BackColor = bass
Return True
Case "Pike"
dgv1.Rows(rowIndex).DefaultCellStyle.BackColor = pike
Return True
Case "Salmon"
dgv1.Rows(rowIndex).DefaultCellStyle.BackColor = salmon
Return True
End Select
Return False
End Function
无论 a) 用户编辑单元格,b) 您更改单元格值 (dgv1.Rows(0).Cells(3).Value = "Mermaid") 或 c) 您更改数据源 (dtParts.Rows(0)(3) = "Pike"),颜色都会更新。
最后,您可以查询DataSource,而不是尝试在蓝色行上循环,在本例中为DataTable:
Dim bassRows = dtSample.Select("Fish = 'Bass'")
For Each dr As DataRow In bassRows
dr("Fish") = "Pike"
Next
颜色会自动改变。