Thursday, July 8, 2010

Highlight GridView Row On MouseOver Using Javascript in Asp.net

Highlight GridView Row On MouseOver Using Javascript in Asp.net

As you knew that Gridview won't gives us the highlighting facility by default but we can achieve highlighting functionality by using simple javascript. To do that we need to use two javascript event. The one is onmouseover event which is also termed as Mouse Hover effect. The another one is onmouseout event. By using this two strong javascript events we will highlight our GridView rows. Ok now we know which javascript event we will use but how we can add these two javascript event handler with our GridView rows? The answer is simple. GridView gives us an event named RowCreated which we can use to bind
javascript event with our GridView rows. Let’s look how we can do this.

To do that first add a page in your project and give the name GridView_Row_Highlight.aspx. Now copy the following HTML markup code into the page:




<asp:GridView ID="GridView_Products" runat="server" AutoGenerateColumns="False"
Width="100%" Font-Names="tahoma" onrowcreated="GridView_Products_RowCreated">
<HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
<RowStyle BackColor="Gray" />
<AlternatingRowStyle BackColor="LightGray" />
<SelectedRowStyle BackColor="Pink" ForeColor="White" Font-Bold="true" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Color" HeaderText="Color" />
<asp:BoundField DataField="Size" HeaderText="Size" />
<asp:CommandField ShowSelectButton="True" />
</Columns>
</asp:GridView>



Now go to the code behind and write following code:

using System;
using System.Web.UI.WebControls;

public partial class GridView_Row_Highlight : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Bind your data in your own way
GridView_Products.DataSource = clsDbUtility.ExecuteQuery("Select * FROM Product");
GridView_Products.DataBind();
}
}
protected void GridView_Products_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// When user moves mouse over the GridView row,First save original or previous color to new attribute,
// and then change it by magenta color to highlight the gridview row.
e.Row.Attributes.Add("onmouseover","this.previous_color=this.style.backgroundColor;this.style.backgroundColor='Magenta'");

// When user leaves the mouse from the row,change the bg color
// or backgroud color to its previous or original value
e.Row.Attributes.Add("onmouseout","this.style.backgroundColor=this.previous_color;");
}
}
}

No comments:

Post a Comment

Popular Posts