TIP: Highlighting ASP.NET 2.0 GridView rows on mouseover (using CSS)

In my example, the GridView definition looks something like the following:

<asp:GridView ID="GridView1" runat="server" AllowSorting="True" AutoGenerateColumns="False"
DataSourceID="odsrcEmp">
<Columns>
.
.
.
</Columns>
<AlternatingRowStyle BackColor="#FFC0C0" />
</asp:GridView>

I added the StyleSheet at the top as following:

<head runat="server">
<title>Untitled Page</title>
<style type = "text/css">
tr.row:hover, tr.over td { background-color: #ffccff; }
</style>
</head>

In the code behind, the following was coded:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
EnableHighLightGrid(Me.GridView1.ClientID)
End If
End Sub

Private Sub EnableHighLightGrid(ByVal GridViewClientID As String)
If Not Page.ClientScript.IsClientScriptBlockRegistered("jsHighLightGridRowsFor" & GridViewClientID) Then
Dim sb As New StringBuilder
sb.AppendLine("<script type=""text/javascript"" language=""javascript"" >")
sb.AppendLine("startHighlight = function()")
sb.AppendLine("{")
sb.AppendLine(" if (document.all && document.getElementById)")
sb.AppendLine(" {")
sb.AppendLine(" navRoot = document.getElementById(""" & GridViewClientID & """);")
sb.AppendLine(" tbody = navRoot.childNodes[0];")
sb.AppendLine(" for (i = 1; i < tbody.childNodes.length; i++)")
sb.AppendLine(" {")
sb.AppendLine(" node = tbody.childNodes[i];")
sb.AppendLine(" if (node.nodeName == ""TR"")")
sb.AppendLine(" {")
sb.AppendLine(" node.onmouseover=function()")
sb.AppendLine(" {")
sb.AppendLine(" this.className = ""over""")
sb.AppendLine(" }")
sb.AppendLine(" node.onmouseout=function()")
sb.AppendLine(" {")
sb.AppendLine(" this.className = this.className.replace(""over"", """");")
sb.AppendLine(" }")
sb.AppendLine(" }")
sb.AppendLine(" }")
sb.AppendLine(" }")
sb.AppendLine("}")
sb.AppendLine("window.onload = startHighlight; ")
sb.AppendLine("</script>")
Page.ClientScript.RegisterClientScriptBlock(Me.GetType, "jsHighLightGridRowsFor" & GridViewClientID, sb.ToString)
End If

I tweaked the above code from beautiful explanation available at http://aspnet.4guysfromrolla.com/articles/021605-1.aspx. Thanks Scott!

Regards,
Jag

About Jag

.NET Architect
This entry was posted in ASP.NET and tagged , . Bookmark the permalink.