ASP.NET: Change GridView's Row Color onMouseOver

Thursday, September 30, 2010

GridView is a good control to display tabular data. Its easy to use GridView's standard built-in templates and have some good formatting with alternate row colrs and other settings. Also, when you have a lot of columns in your table its always handy if the row is highlighted when you put your mouse over to it. GridView does not has that feature built into it, but its really easy to add it by adding some code into the RowDataBound event of the GridView. Here is how the code will look like in the code behind:

// C#
protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
// Creating hover effects on mouseover event for each row
if (e.Row.RowType == DataControlRowType.DataRow)
e.Row.Attributes["onmouseover"] = "'#D1DDF1';";

if ((e.Row.RowIndex % 2) == 0) // if even row
e.Row.Attributes["onmouseout"] = "'#EFF3FB';";
else // alternate row
e.Row.Attributes["onmouseout"] = "'White';";
' VB.Net
Protected Sub gridView_RowDataBound(sender As Object, e As GridViewRowEventArgs)
' Creating hover effects on mouseover event for each row
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Attributes("onmouseover") = "'#D1DDF1';"

If (e.Row.RowIndex Mod 2) Is 0 Then
' if even row
e.Row.Attributes("onmouseout") = "'#EFF3FB';"
' alternate row
e.Row.Attributes("onmouseout") = "'White';"
End If
End If
End Sub

The code above, adds the 'onmouseover' and 'onmouseout' attributes to each of the table rows in GridView. Make sure you match the onmouseout colors to the colors in your original template. You can also use the 'onclick' attribute instead of 'onmouseover' if you want to change the color on clicking a row.

This feature could also be potentially implemented on client-side using jQuery and CSS. If you'd like to do it that way, use the 'onmouseover' or 'onclick' event of jQuery to change your row colors and then change them back in the 'onmouseout' event.