Highlight GridView Row On MouseOver Using Javascript

2:23:00 am 0 Comments

Highlight GridView Row On MouseOver Using Javascript

If you want to highlight rows in Gridview on mouse hover or mouseover event by using client side javascript than you can do it in following way.



For this we need to create a css class and define the color we want to use for highlighting in html source of page.

<style type="text/css">
.normal
{
background-color:white;
}
.highlight
{
background-color:#cccccc;
}
</style>


html source of the whole page is like

<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.normal
{
background-color:white;
}
.highlight
{
background-color:#cccccc;
}
</style>


</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />


<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
OnRowCreated="GridView1_RowCreated">
<SelectedRowStyle BackColor="BurlyWood" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Name" HeaderText="Name"
SortExpression="Name" />
<asp:BoundField DataField="City" HeaderText="City"
SortExpression="City" />
<asp:BoundField DataField="Country" HeaderText="Country"
SortExpression="Country" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Name], [City], [Country] FROM [Location]">
</asp:SqlDataSource>
<br />
<div>
</div>
</form>
</body>
</html>


Now in code behind file we need to add the onmouseover and onmouseout attributes to rows of gridview.

For this we need to use RowCreated event of Gridview

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataBind();
}


}
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.className='highlight'");
e.Row.Attributes.Add("onmouseout", "this.className='normal'");
}


}


Now row will be highlighted on mouse hover

Download the sample code

0 comments: