How to get DataGridView Row back color to change
I have a DataGridView control with
dgridView.DataSource = QueryCustomers(LastName) // return IList from LINQtoSql
I am using the following to alter Row BackColor:
Private Sub dgridView_OnPrePaint(ByVal sender As System.Object, ByVal e As DataGridViewRowPrePaintEventArgs) Handles dgridView.RowPrePaint
Dim dgridRow As DataGridViewRow = dgridView.Rows(e.RowIndex)
Select Case dgridRow.Cells("Status").Value
Case "Alpha"
dgridRow.DefaultCellStyle.BackColor = Color.LightGreen
Case "Beta"
dgridRow.DefaultCellStyle.BackColor = Color.LightGreen
Case "Terminated"
dgridRow.DefaultCellStyle.BackColor = Color.Salmon
Case Else
If currentColor = Color.White Then
dgridRow.DefaultCellStyle.BackColor = Color.Silver
Else
dgridRow.DefaultCellStyle.BackColor =开发者_StackOverflow社区 Color.White
End If
currentColor = dgridRow.DefaultCellStyle.BackColor
End Select
End Sub
This seems to work except that with certain queries, the DataGridView will continue to flicker until I edit a row and save. Editing is performed by double-clicking one of the rows causing a WinForm to display over the main form containing the DataGridView. Once I save the data, and data changes in the data grid, the flickering stops.
Is there a better way to color the rows? I don't want to iterate the DataGridView everytime something changes. It seems like subscribing to the RowPrePaint event would be the thing to do. Do I need to subscribe to the RowPostPaint?
NOTE: answers can be C# or VB.Net.
This may be a bit too late.. but I'd rather you do the formatting after the grid has been populated with data with a loop for each of the grid's Rows.
Like so:
for each dr as datagridviewrow in me.dgridrow.rows
'condition for each row based on cell's input is put here
if dgridRow.Cells("Status").Value = "Alpha" then
dr.defaultcellstyle.backcolor = color.lightgreen
end if
next
Yep... hope that help anyone in the future..
精彩评论