How to change the background color of a grid cell based on its value
I need to change the background color of the cells in my gridview, but it doesn't work.
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView2.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
For Each er As GridViewRow In GridView2.Rows
If er.Cells(4).Text = "Formation" Then
er.Cells(4).BackColor = Color.Red
End If
Next
End If
End Sub
How can I change the background color of a cell based on its value?
+3
source to share
2 answers
Try the following:
Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView2.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.Cells(4).Text = "Formation" Then
e.Row.Cells(4).BackColor = Color.Red
End If
End If
End Sub
Also add a breakpoint on
If e.Row.Cells(4).Text = "Formation" Then
and check the value e.Row.Cells(4).Text
and make sure it's really = "Formation"
, maybe you need to get the value of the label that is in cells (4).
+1
source to share
try event CellFormatting
and remove for each one. The event is triggered for every cell.
Private Sub grd_CellFormatting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles GridView2.CellFormatting
If GridView2.Item(4,e.RowIndex).Value = "Formation" Then
e.CellStyle.BackColor = Color.Red
End If
End Sub
+1
source to share