Sunday 22 May 2011

Highlighting GridView row on mouse over using Javascript


This post concentrates on highlighting the GridView rows when the mouse moving on it. In GridView we don’t have that futures, but highlighting the row will help the user which row he/she is moving on. Addition to this, this implementation will also selects the particular row when click on the row. So the use case would be:

  1. When a mouse is hovering on a particular row, the background color of the row must be changed to predefined color.
  2. When the mouse is out from the Row, the background color must be reverted back to the old color before highlighting it.
  3. When clicking a particular row on any column, the row must be selected and the row color must be changed to SelectedRowStyle color defined with the GridView. The execution of the code must call the SelectedIndexChanged event.

To implement this functionality, I have two types of example.
  1. Define and set the background color using Javascript when mouse hover on it and set the old color back when mouse is out.
  2. When the Row colors are defined using CSS style, the javascript must set and rollback the css class only. But considering the code functionality both are same.

I am using Northwind database for this example, so please make sure you have the same database to test the code.

First example (using color code):

The GridView script would be
<asp:GridView ID="grdViewProducts" runat="server"
    AllowPaging="True" AutoGenerateColumns="False" TabIndex="1"
    DataKeyNames="ProductID" Width="100%" BackColor="White" 
    CellPadding="3" BorderStyle="Solid" BorderWidth="1px" BorderColor="Black" 
    onrowdatabound="grdViewProducts_RowDataBound" 
    onpageindexchanging="grdViewProducts_PageIndexChanging" 
    onselectedindexchanged="grdViewProducts_SelectedIndexChanged" 
    GridLines="Horizontal">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" >
            <ItemStyle Width="30%" />
        </asp:BoundField>
        <asp:BoundField DataField="CompanyName" HeaderText="Supplier" >
            <ItemStyle Width="25%" />
        </asp:BoundField>
        <asp:BoundField DataField="CategoryName" HeaderText="Category" >
            <ItemStyle Width="20%" />
        </asp:BoundField>
        <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit">
            <ItemStyle Width="15%" />
        </asp:BoundField>
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" DataFormatString="{0:#0.00}">
            <ItemStyle Width="15%" />
        </asp:BoundField>
    </Columns>
    <RowStyle BackColor="White" ForeColor="#333333" />
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Right" />
    <SelectedRowStyle BackColor="#A5D1DE" Font-Bold="true" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="#E2DED6" ForeColor="#284775" />
</asp:GridView>

The Code behind
/// <summary>
/// Method which binds the data to the Grid
/// </summary>
private void BindGrid()
{
    using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString))
    {

        SqlCommand command = new SqlCommand(
               "SELECT ProductID, ProductName, CompanyName, CategoryName, " +
               "QuantityPerUnit, UnitPrice FROM Products " +
               "JOIN Suppliers ON Products.SupplierID = Suppliers.SupplierID " +
               "JOIN Categories ON Products.CategoryID = Categories.CategoryID ", connection);

        connection.Open();
        SqlDataReader dr = command.ExecuteReader(CommandBehavior.CloseConnection);

        IList<ProductView> productViewList = new List<ProductView>();
        while (dr.Read())
        {
            ProductView productView = new ProductView();
            productView.ProductID = Convert.ToInt32(dr["ProductID"].ToString());
            productView.ProductName = dr["ProductName"].ToString();
            productView.CompanyName = dr["CompanyName"].ToString();
            productView.CategoryName = dr["CategoryName"].ToString();
            productView.QuantityPerUnit = dr["QuantityPerUnit"].ToString();
            productView.UnitPrice = Convert.ToDouble(dr["UnitPrice"].ToString());
            productViewList.Add(productView);
        }
        grdViewProducts.DataSource = productViewList;
        grdViewProducts.DataBind();
    }
}

protected void grdViewProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
    // For changing the color when mouse is moving on the row
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        e.Row.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
        e.Row.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";
        e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdViewProducts, "Select$" + e.Row.RowIndex);
    }
}
protected void grdViewProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    grdViewProducts.SelectedIndex = -1;
    grdViewProducts.PageIndex = e.NewPageIndex;
    BindGrid();
}

protected void grdViewProducts_SelectedIndexChanged(object sender, EventArgs e)
{
            
}

If you look at the RowDataBound of GridView grdViewProducts_RowDataBound, we have the code to define the mouseover, mouseout and onclick Javascript events. Incase if you dont required to select a particular row by click on it, you can remove the onclick (ie., e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdViewProducts, "Select$" + e.Row.RowIndex)) line.

The Javascript
// variable to hold the existing color of GridView row
var oldgridSelectedColor;

// Function to set the background color when mouse is over
function setMouseOverColor(element) {
    oldgridSelectedColor = element.style.backgroundColor;
    element.style.backgroundColor = '#ffdf84'; // this is the color I am seting as backcolor
    element.style.cursor = 'pointer';
}

// Function to set the existing color when over is out of the row
function setMouseOutColor(element) {
    element.style.backgroundColor = oldgridSelectedColor;
}

The ProductView entity class
public class ProductView
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string CompanyName { get; set; }
    public string CategoryName { get; set; }
    public string QuantityPerUnit { get; set; }
    public double UnitPrice { get; set; }
}

Second Example
The second implementation also looks same. But instead of directly defining the color values, we will be defining the css class.
<asp:GridView ID="grdViewProducts" runat="server"
    AllowPaging="True" AutoGenerateColumns="False" TabIndex="1"
    DataKeyNames="ProductID" Width="100%" BackColor="White" 
    CellPadding="3" BorderStyle="Solid" BorderWidth="1px" BorderColor="Black" 
    onrowdatabound="grdViewProducts_RowDataBound" 
    onpageindexchanging="grdViewProducts_PageIndexChanging" 
    onselectedindexchanged="grdViewProducts_SelectedIndexChanged" 
    GridLines="Horizontal">
    <Columns>
        <asp:BoundField DataField="ProductName" HeaderText="Product Name" >
            <ItemStyle Width="30%" />
        </asp:BoundField>
        <asp:BoundField DataField="CompanyName" HeaderText="Supplier" >
            <ItemStyle Width="25%" />
        </asp:BoundField>
        <asp:BoundField DataField="CategoryName" HeaderText="Category" >
            <ItemStyle Width="20%" />
        </asp:BoundField>
        <asp:BoundField DataField="QuantityPerUnit" HeaderText="Quantity Per Unit">
            <ItemStyle Width="15%" />
        </asp:BoundField>
        <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" DataFormatString="{0:#0.00}">
            <ItemStyle Width="15%" />
        </asp:BoundField>
    </Columns>
    <RowStyle CssClass="RowStyle" />
    <FooterStyle CssClass="FooterStyle" />
    <PagerStyle CssClass="PagerStyle" />
    <SelectedRowStyle CssClass="SelectedRowStyle" />
    <HeaderStyle CssClass="HeaderStyle" />
    <AlternatingRowStyle CssClass="AlternatingRowStyle" />
</asp:GridView>

The Css style
.RowStyle
{
    background-color:White;
    color:#333333;
}
.FooterStyle
{
    background-color:#5D7B9D;
    font-weight:bold;
    color:White;
}
.PagerStyle
{
    background-color:#284775;
    color:White;
    text-align:right;
}
.SelectedRowStyle
{
    background-color:#A5D1DE;
    font-weight:bold;
    color:#333333;
}
.HeaderStyle
{
    background-color:#5D7B9D;
    font-weight:bold;
    color:White;
}
.AlternatingRowStyle
{
    background-color:#E2DED6;
    color:#284775;
}
.MouseOverStyle
{
    background-color:#ffdf84;
}

The Javascript
// variable to hold the existing color of GridView row
var oldgridSelectedColor;

// Function to set the background color when mouse is over
function setMouseOverColor(element) {
    oldgridSelectedColor = element.className;
    element.className = 'MouseOverStyle';
    element.style.cursor = 'pointer';
}

// Function to set the existing color when over is out of the row
function setMouseOutColor(element) {
    element.className = oldgridSelectedColor;
}

The Code behind
protected void grdViewProducts_RowDataBound(object sender, GridViewRowEventArgs e)
{
 // For changing the color when mouse is moving on the row
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  e.Row.Attributes["onmouseover"] = "javascript:setMouseOverColor(this);";
  e.Row.Attributes["onmouseout"] = "javascript:setMouseOutColor(this);";
  e.Row.Attributes["onclick"] = ClientScript.GetPostBackClientHyperlink(this.grdViewProducts, "Select$" + e.Row.RowIndex);
 }
}
protected void grdViewProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
 grdViewProducts.PageIndex = e.NewPageIndex;
 BindGrid();
}

protected void grdViewProducts_SelectedIndexChanged(object sender, EventArgs e)
{

}
This code has been tested with IE 6.0/8.0, Chrome 10.0, Firefox 3.6, Opera 11.01

Here is the output of the example.
Initial GridView when it shows

Highlighting the GridView row on mouse is over on it

The selected row changed to different color
You can see the output in video here



download the working example of the source code in C# here and in VB here

5 Responses to “Highlighting GridView row on mouse over using Javascript”

  • Bella says:
    31 May 2011 at 10:50

    Can you send me the source code Please?
    My email: b020910196@student.utem.edu.my
    thx...

  • Thirumalai M says:
    1 June 2011 at 22:27

    Hi Bella. The source code sent to the mentioned mail id. Pls check

  • Bella says:
    7 June 2011 at 08:23

    hi thiru.
    thx 4 ur source code...:D

  • Anonymous says:
    9 March 2012 at 13:46

    Hi Thiru,

    Can you please the souce code in VB to rogerwong_cj@yahoo.com.sg

    Many thanks.

  • Thirumalai M says:
    10 March 2012 at 21:18

    Hi, Code has been sent. Please verify...

Post a Comment