Highlight GridView Row OnMouseOver

May 31, 2008 09:58 by wjchristenson2

A common request I see for the GridView control is to highlight the row when the user hovers over it.  The GridView does not come pre-packaged with this functionality and it is up to us to make it happen.  I am going to assume that we already have a GridView present on our web page and we have data binding to it.

What we basically want to do is add some Javascript to the row so when the user hovers over the row it changes colors.  Here's the code:

Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
    'ensure the row is a datarow and is not the edit row
    If e.Row.RowType = DataControlRowType.DataRow And e.Row.RowIndex <> Me.GridView1.EditIndex Then
        e.Row.Attributes.Add("onmouseover", "changeBackColor(this, true, ""#DFE8F6"");")
        e.Row.Attributes.Add("onmouseout", "changeBackColor(this, false, """");")
    End If
End Sub

First we handle the RowDataBound event of the GridView.  The RowDataBound event fires when a data row is bound to data.  At this point we can tap into every row that is created by the GridView control.  However, we only desire to highlight data rows that are not in edit mode.  Due to this, in line 3 we filter out rows we don't want.  In lines 4 & 5 we add attributes to the row to call our changeBackColor() javascript function. 

Here is our javascript on the .aspx page:

var lastColorUsed;
function changeBackColor(row, highlight, color) {
    if (highlight) {
        lastColorUsed = row.style.backgroundColor;
        row.style.backgroundColor = color;
    } else {
        row.style.backgroundColor = lastColorUsed;
    }
}

In line 1 we declare a variable to remember what the last color was.  The reason we do this is so that when the mouse pointer exits the scope of the row, we want to change the background color of the row to what it was previously.  So, if we are highlighting, we save the current color of the row and change the background color of the row to the highlight color.  When the mouse exits the row, we change the background color of the previously highlighted row back to what it was originally.

Examples_Soln.zip (70.47 kb)

Bookmark and Share