[2008] DataGridView conditional formatting - ok, but ...
I'm using what I think is a workaround for conditional formatting of a DataGridView. There must be a better way.
The problem I had was that when the user made a checkbox in column 0 = false, I couldn't get the overriding row style for the row to revert the normal/alternating style used by the grid. I can't believe that the code shown below is the best way of doing this, i.e. determining if the row index is odd or even, and then styling the row accordingly.
If anybody can help tidy this up a bit, it would be appreciated.
Thanks in advance.
Code:
Private Sub dgvCSVPreparation_CellMouseUp(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) _
Handles dgvCSVPreparation.CellMouseUp
' Detect changes to checkbox column
If TypeOf Me.dgvCSVPreparation.CurrentCell Is DataGridViewCheckBoxCell Then
dgvCSVPreparation.EndEdit()
Dim blnCellVal As Boolean = DirectCast(dgvCSVPreparation.CurrentCell.Value, Boolean)
If blnCellVal Then
Me.dgvCSVPreparation.CurrentRow.Selected = True
End If
End If
End Sub
Private Sub dgvCSVPreparation_CellFormatting(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
Handles dgvCSVPreparation.CellFormatting
With Me.dgvCSVPreparation
.DefaultCellStyle.BackColor = Color.White
.DefaultCellStyle.ForeColor = Color.Black
.AlternatingRowsDefaultCellStyle.BackColor = Color.WhiteSmoke
.AlternatingRowsDefaultCellStyle.ForeColor = Color.Black
End With
With Me.dgvCSVPreparation.Rows(e.RowIndex)
If .Cells(0).Value = True Then
.DefaultCellStyle.BackColor = Color.Black
.DefaultCellStyle.ForeColor = Color.White
End If
End With
End Sub
Private Sub dgvCSVPreparation_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvCSVPreparation.CellValueChanged
With Me.dgvCSVPreparation.Rows(e.RowIndex)
If e.RowIndex Mod 2 = 0 Then
' Even number
.DefaultCellStyle.BackColor = Color.White
.DefaultCellStyle.ForeColor = Color.Black
Else
' Odd number
.DefaultCellStyle.BackColor = Color.WhiteSmoke
.DefaultCellStyle.ForeColor = Color.Black
End If
End With
End Sub