tags:

views:

389

answers:

1

When databinding to an ASP .NET GridView, how does one change the background color, based on a boolean value that is a column in the data table that the GridView is bound?

For instance if you are bound to a table that has two columns: Name, LikesBurritos. And you want to have the labels of people's names be Blue if they like burritos and white if they don't.

Iterating through the data table or list of objects defeats the purpose of databinding... And there are lots of places we use databinding for the express point of not coding the add of every column while iterating through the set. I'm curious if you can do this declaritivly by using an expresion in the markup...

+5  A: 

Use the RowDataBound event built into the GridView, then you could do something like this (in VB.NET):

Private Sub FormatGridView(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
        Handles gvBurritoPeople.RowDataBound

  Dim drBurritoPeople As BurritoPeopleRow

  If e.Row.RowType = DataControlRowType.DataRow Then

     drBurritoPeople = DirectCast(DirectCast(e.Row.DataItem, System.Data.DataRowView).Row, BurritoPeopleRow)

     If drBurritoPeople.LikesBurritos Then
        e.Row.CssClass = "BlueRow"
     Else
        e.Row.CssClass = "WhiteRow"
     End If         

  End IF

End Sub

I'm not quite sure what your implications are about not wanting to iterate through all the data, but this rendering of the white or blue row is occurring at the same time as the data is written to the page, so you're not losing any performance here.

EDIT: I guess one potential alternative to this would be to create a third column in your ResultSet that contains a CssClass name that you could declare based on the the LikesBurritos column and you could bind the CssClass to that in your GridView, but this is going to require you to have access to the SQL statement or to intercept your DataBinding process to modify the ResultSet coming down.

Dillie-O