The Disturbed Buddha

Simple Observations of a Self-proclaimed Novice

Highlighting a GridView Row When Clicking a CheckBox

You’ve seen it in Yahoo!® Mail and numerous other places.  When you click a CheckBox next to an item, that item’s row changes color.  When you uncheck the box, the row returns to its original color.


Highlighting GridView Rows


Basically, we just need to attach a bit of JavaScript to handle the click event of each CheckBox in the GridView.  Here is the JavaScript, if you were to see it by itself:

<script type="text/javascript"> 
    if (this.checked) { 
    } else { 

Notice that we’re setting the background color to an empty string when the CheckBox is unchecked.  We do this because we only want to remove the extra styling that we added.  That way, if your GridView has alternating row styles, it will go back to its original color.


We are going to attach this event handler during the RowDataBound event of the GridView.  First, we check to make sure that it is a DataRow that we’re dealing with and not a header or footer.  Then we build the JavaScript using a StringBuilder (which you should use any time that you’re doing string concatenation).  We get the row’s ID from the arguments that were passed into the RowDataBound method:  e.Row.ClientID


We then just have to use the FindControl method on the current row and add the event and our JavaScript as an attribute to the CheckBox.  Simple as that!



Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    If (e.Row.RowType = DataControlRowType.DataRow) Then 
        Dim script As New StringBuilder 
        script.Append("if (this.checked) {") 
        script.Append("} else {") 
        CType(e.Row.Cells(0).FindControl("CheckBox1"), CheckBox).Attributes.Add("onclick", script.ToString) 
    End If 
End Sub

I’m sure that you can see how this code could easily be built upon to include fading in/fading out of the color or any other UI effect.


January 31, 2008 Posted by | ASP.NET, Javascript, Web Development | 1 Comment