Conditional Formatting in a GridView
This code will allow you to change the background colour of a cell or entire row depending on certain conditions.
In this example we test if the row being bound is a data row, then if the second column (indexed as 1) is equal to 0. If it is then the row’s backcolor is set as PeachPuff and the cell itself has backcolor Salmon. Remember that cell indexing starts at 0 so that the first column is e.Row.Cells(0), the second column e.Row.Cells(1), etc.
Protected Sub grdTable_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grdTable.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
If e.Row.Cells(1).Text = “0″ Then
e.Row.BackColor = System.Drawing.Color.PeachPuff
e.Row.Cells(1).BackColor = Drawing.Color.Salmon
End If
End If
End Sub
To change the text colour simply substitute BackColor with ForeColor.
| Print article | This entry was posted by admin on December 17, 2009 at 11:58 am, and is filed under ASP.NET, Cells, GridView, Row. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |


about 4 months ago
If we assume that the third row, indexed as 2, contains the Boolean CheckBox column, I think this should work for a CheckBox:
If e.Row.RowType = DataControlRowType.DataRow Then
Dim chkTest As New CheckBox
chkTest = CType(e.Row.Cells(2).Controls.Item(0), CheckBox)
If chkTest.Checked = True Then
e.Row.BackColor = System.Drawing.Color.PeachPuff
e.Row.Cells(1).BackColor = Drawing.Color.Salmon
End If
End If
about 4 months ago
I think Celine asked about a CheckBox… I would like to know too! Checkbox.checked – or something to that effect.
Thanks
about 5 months ago
You could simply use:
If txtTextBox.Text = “0″ Then
txtTextBox.BackColor = Drawing.Color.Salmon
End If
If you wanted to check for a TextBox containing a particular string you could use:
If txtTextBox.Text.Contains(“0″) Then
txtTextBox.BackColor = Drawing.Color.Salmon
End If
To change the colour as the text is typed would harder but could be done using JavaScript.
about 5 months ago
Thanks! that worked great. How would you go about for a check box?