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.

About Chris Smith

Web developer specialising in frontend UI design @chris22smith
This entry was posted in ASP.NET, Cells, GridView, Row and tagged , , , , , , . Bookmark the permalink.

6 Responses to Conditional Formatting in a GridView

  1. Pingback: Conditional Formatting in a GridView

  2. admin says:

    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

  3. sean says:

    I think Celine asked about a CheckBox… I would like to know too! Checkbox.checked – or something to that effect.
    Thanks

  4. admin says:

    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.

  5. Celine says:

    Thanks! that worked great. How would you go about for a check box?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>