我有一个datagridview控件,我需要根据每行的一个单元格中的值为行着色。我使用的是CellFormatting事件,像这样:当网格排序时,DataGridView.CellFormatting不起作用
Private Sub DGDisplay_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles dgDisplay.CellFormatting
Dim intRowIndex As Integer = e.RowIndex 'This is zero when sorting.....
Dim CurrentRow As DataGridViewRow = dgDisplay.Rows(intRowIndex)
Dim strTestValue As String = CurrentRow.Cells("Status").Value
Select Case UCase(strTestValue)
Case "WARNING"
CurrentRow.DefaultCellStyle.BackColor = Color.PeachPuff
Case "ERRMESSAGE"
CurrentRow.DefaultCellStyle.BackColor = Color.Salmon
End Select
End Sub
此工作正常时,电网负荷,当我把它的滚动,等等。但是当我在列标题点击排序的网格,e.RowIndex总是零和所有的行得到第一行的格式...
为什么这不工作时,网格排序?
编辑: 的Joakim是在正确的轨道上,但下面的代码工作正常:
Private Sub dgDisplay_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles dgDisplay.CellPainting
If e.RowIndex < 0 Then
Exit Sub
End If
Dim intRowIndex As Integer = e.RowIndex
Dim CurrentRow As DataGridViewRow = dgDisplay.Rows(intRowIndex)
Dim strTestValue As String = CurrentRow.Cells("Status").Value
Select Case UCase(strTestValue)
Case "WARNING"
CurrentRow.DefaultCellStyle.BackColor = Color.PeachPuff
Case "ERRMESSAGE"
CurrentRow.DefaultCellStyle.BackColor = Color.Salmon
End Select
End Sub
出于某种原因,e.RowIndex设置正确,在这里,但没有其他方法。你唯一需要担心的是它可以是-1。但是当我尝试使用其他方法时,包括PrePaint,我必须处理它总是在某种程度上变为零。如果我排除零情况,就像我排除了负面情况一样,那么第一行总是白色!疯狂......我不确定这是为什么起作用,但它确实如此。它也不会产生超出我使用CellFormatting事件的闪烁。
如果任何人都能解释这个原因为什么e.RowIndex正在做这么一个伟大的或提供一个更好的方式来做到这一点,他们会得到答案!
更新:我尝试使用DataGridView.Paint事件,并通过循环行。虽然这可行,但会导致行首先以其原始颜色显示,然后更改为适当的颜色。 CellFormatting事件可能是正确的使用然后,但上述问题发生... – John