In this article I will explain how to highlight ASP.Net GridView Row Color on Mouseover using jQuery in ASP.Net.
In order to implement GridView Row highlighting, jQuery Hover event handler is used, so that when mouse is moved over GridView Row its background color is changed so that the GridView Row looks highlighted and when mouse is moved out its color is changed back to normal like other GridView Rows.
HTML Markup
The HTML Markup consists of an ASP.Net GridView with two columns.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
Namespaces
You will need to import the following namespaces.
Binding the GridView
I have made use of DataTable with some dummy values for this article.
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Changing the GridView Row Background color when clicked using JavaScript
In the below JavaScript code snippet, I have made use of jQuery to make the job easier. Firstly I have attached jQuery Hover event handler to the TD i.e. Cell of the GridView. When mouse is moved over some GridView Cell within a Row, using the reference of the Cell the Row of the GridView is determined.
Then the hover_row CSS class is applied to the Row to which the Cell belongs i.e. the Current Row on which the mouse was hovered, this is implemented using the closest function of jQuery which can be used to determine the closest parent here the closest TR element.
The hover_row CSS class is used to apply color to the GridView Row.
<script type="text/javascript">
$(function () {
$("[id*=GridView1] td").hover(function () {
$("td", $(this).closest("tr")).addClass("hover_row");
},function(){
$("td", $(this).closest("tr")).removeClass("hover_row");
});
});
</script>
CSS Classes used to style the GridView
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
td
{
cursor: pointer;
}
.hover_row
{
background-color: #A1DCF2;
}
</style>
Default GridView Row color
GridView Row color on mouseover
Demo
Downloads