Using ASP.NET and jQuery to Highlight a Row in GridView without a PostBack

Posted by: Suprotim Agarwal , on 12/30/2008, in Category jQuery and ASP.NET
Views: 94076
Abstract: In one of our previous articles, we had seen how to highlight a row in GridView using JavaScript without causing a postback. In this article, we will simplify the approach using jQuery, without the need of handling any of the GridView events.
Using ASP.NET and jQuery to Highlight a Row in GridView without a PostBack
 
In one of our previous articles Highlight a Row in GridView without a postback using ASP.NET and JavaScript, we had seen how to highlight a row in GridView without causing a postback. We had made use of the GridView ‘RowCreated’ event and added the onMouseOver and the onMouseOut events to enable the row to change its color whenever the mouse is over a particular row.
In this article, we will simplify the approach using jQuery, without the need of handling any of the GridView events. If you are new to jQuery, I would strongly suggest you to check this: Using jQuery with ASP.NET - A Beginner's Guide
Open Visual Studio 2008 > File > New > Website > Choose ‘ASP.NET 3.5 website’ from the templates > Choose your language (C# or VB) > Enter the location > Ok. In the Solution Explorer, right click your project > New Folder > rename the folder as ‘Scripts’.
Right click the Scripts folder > Add Existing Item > Browse to the path where you downloaded the jQuery library (jquery-1.2.6.js) and the intellisense documentation (jquery-1.2.6-vsdoc.js) > Select the files and click Add.
Now drag and drop the jquery-1.2.6.js file from the Solution Explorer to the <head> section of your page to create a reference as shown below:
<head runat="server">
    <title></title>
    <script src="Script/jquery-1.2.6.js" type="text/javascript"></script>
   
Drag and drop a SqlDataSource Control to the Default.aspx page and use the wizard to connect to the Northwind database. Select the CustomerId, CompanyName, ContactName, Address and City from the Customers table. The wizard will also prompt you to save the connection string in the web.config file. Choose to do so. The design code will look similar to the following:
           <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
                SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
            </asp:SqlDataSource>
An entry will be added to the web.config file as shown below:
 <connectionStrings>
    <add name="NorthwindConnectionString"
         connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True"
         providerName="System.Data.SqlClient"/>
 </connectionStrings>
Now add a GridView control to the page and using the smart tag, select the DataSource to be SqlDataSource1 in the GridView tasks panel. Using the same panel, click on the Enable Paging and Enable Sorting checkboxes. The source will look similar to the following. Observe that the DataKeyNames is set to ‘CustomerId’, that is the primary key of the Customers table
       <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
            DataSourceID="SqlDataSource1" AllowPaging="True" AllowSorting="True">
            <Columns>                          
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True" SortExpression="CustomerID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName" SortExpression="ContactName" />
                <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
            </Columns>
        </asp:GridView>
To enable row highlighting, we will follow two approaches. In the first approach we will make the GridView generate the <thead> so that the header is not highlighted. GridView by default generates the header as a <th> inside a <tr>.
First Approach
All we need to do is to add the following lines of jQuery code in the <head> section of the page
   <script type="text/javascript">
 
        $(document).ready(function() {       
            $("table tr:has(td)").css({ background: "ffffff" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#ffffff" }); }
                );
        });
    </script>
We have used the ‘hover’ event in jQuery. More about the hover event can be read over here.
In order to prevent the Column Header to be highlighted, use the following code to generate the <thead>:
C#
        if (GridView1.Rows.Count > 0)
        {
            GridView1.UseAccessibleHeader = true;           
            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
            //GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
        }
VB.NET
            If GridView1.Rows.Count > 0 Then
                  GridView1.UseAccessibleHeader = True
                  GridView1.HeaderRow.TableSection = TableRowSection.TableHeader
                  'GridView1.FooterRow.TableSection = TableRowSection.TableFooter;
            End If
The code above generates the <thead> tag for us instead of generating the <th> in the <tr> (which is the default html generated). I have on purpose commented out the FooterRow code, since it gives me a strange error. I have used a second approach to solve that to a certain extent. Read on.
Second Approach
If you do not want to write all that code to generate the <thead> and then filter it out, here's a pure jQuery solution to it. I found this solution in a jQuery forum where a user had posted a similar issue. Karl Swedberg proposed the solution as given below. Add the following lines of jQuery code in the <head> section of the page:
<script type="text/javascript">
$(document).ready(function() {
$("tr").filter(function() {
return $('td', this).length && !$('table', this).length
}).css({ background: "ffffff" }).hover(
function() { $(this).css({ background: "#C1DAD7" }); },
function() { $(this).css({ background: "#ffffff" }); }
);
});
That’s it. Run the application and you will observe that the row gets highlighted when the user hovers the mouse on a row.
jQuery Highlight
I hope this article was useful and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by dec853 on Tuesday, December 30, 2008 6:01 PM
hovering highlights all rows one at a time until all rows are highlighted including the header row.
Comment posted by John Boker on Thursday, January 1, 2009 9:48 AM
This method will highlight any row of any table on the page, if that's not what's wanted you might want to wrap the gridview in a <div class="gridview"> or something then use $(".gridview table tr").css(...) for the row highlighting.
Comment posted by Suprotim Agarwal on Tuesday, January 6, 2009 1:02 AM
dec853, John: Thanks for your comments. To avoid highlighting the header row, there is a simple solution. Just make the GridView generate <thead> instead of the <th>
by using the following line of code:

GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
Comment posted by http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm on Friday, January 9, 2009 5:56 AM
http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm
Comment posted by http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm on Friday, January 9, 2009 5:56 AM
http://www.java2s.com/Code/JavaScript/GUI-Components/Checkboxtreenodecheckeduncheckedgetthecheckeditems.htm
Comment posted by Janko on Saturday, January 17, 2009 5:38 AM
Fantastic! I was searching for something like this and both your solutions work well. I find a problem though when I hover over the pager control. Any solutions?
Comment posted by Muhammad Iqbal on Sunday, January 18, 2009 12:27 PM
This functionality can be done very easly as below mentioned.
At gridview row databound event determine the row type and register the javascript code for that row.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            #region HighLight Row on MouseOver

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
               e.Row.Attributes.Add("onMouseOver", "Highlight(this)");
               e.Row.Attributes.Add("onMouseOut", "UnHighlight(this)");
            }
            #endregion
        }
Add it in Page html file...
<script type="text/javascript">
    
     /***** HightLight Gridview Rows on MouseOver ****/
     function Highlight(row)
     {
        row.style.backgroundColor = '#e7f2fd';
     }
     function UnHighlight(row)
     {
        row.style.backgroundColor ='#FFF';        
     }
</script>

lool enjoy it..
Comment posted by John Harcourt on Tuesday, February 24, 2009 4:29 PM
Nice. However, my gridview has alternating colors for the odd rows. How can this work, maintaining the original background of the rows?
Comment posted by KansasCoder on Wednesday, March 18, 2009 11:09 AM
How could something like this be donw when the original grid uses Alternating Row  Styles?
Comment posted by KansasCoder on Wednesday, March 18, 2009 11:11 AM
It would just call a jquery function that would capture the initial rowcolor onmouseover before changing it and then pass that to the onmouseout.
Comment posted by atlantic on Monday, March 23, 2009 3:10 AM
i have a question,when i use Repeater or DataList,i think this way could not do that,how can i do that,thank you very much.
Comment posted by jimmyc on Monday, March 23, 2009 5:55 PM
Is anyone else experiencing this failing after a page postbacks?
Comment posted by Suprotim Agarwal on Tuesday, March 24, 2009 2:58 AM
Jimmyc: Yes the rows will no longer remain highlighted if there is a postback. That's the default behavior. To persist the highlight during a postback, you would need to keep track of the rows that were highlighted (in a collection) and then re-highlight them using code.
Comment posted by jimmyc on Tuesday, March 24, 2009 9:35 AM
If you are experiencing a problem with the jquery not working after a postback try this code instead for the second approach:
[code]
    protected void Register_JQueryScripts()
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"<script type=""text/javascript"">");
        sb.Append(@"function pageLoad() {");
        sb.Append(@"$(""#gridView table tr"").filter(function() {");
        sb.Append(@"return $('td', this).length && !$('table', this).length");
        sb.Append(@"}).css({ background: ""ffffff"" }).hover(");
        sb.Append(@"function() { $(this).css({ background: ""#C1DAD7"" }); },");
        sb.Append(@"function() { $(this).css({ background: ""#ffffff"" }); }");
        sb.Append(@");");
        sb.Append(@"}");
        sb.Append(@"</script>");

        if (!ClientScript.IsStartupScriptRegistered("JSScript"))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());
        }
    }
[/code]
Comment posted by Suprotim Agarwal on Thursday, March 26, 2009 8:47 AM
jimmc: Thanks. I will try this out!
Comment posted by Jerry Hong on Thursday, May 14, 2009 9:46 PM
First, thanks your post, it's useful for me, recently, I'm just finding some simple code to do the 'Height' effect, and I found you're using the 'table' DOM factor, but I just want the GridView or someone type of control to do this, but not all, I think it will have some problems sometimes. I'm interesting in the 'Skin', it seems can do so, but need to add some custom event to GridView, like 'onmouseover' etc., and that's the problem, event I have correctly add some script but it seems the effect is strange. Do anyone have some other good idea? Thanks in advance.
Comment posted by Nimesh on Monday, July 6, 2009 5:32 AM
That's a nice code. I used jQuery for the first time and I liked it. Thanks.
Comment posted by Nimesh on Monday, July 6, 2009 6:37 AM
I'm using the second method mentioned above. How can we restrict this hover functionality only for a specific table, with the id gdReports?
Comment posted by Suprotim Agarwal on Friday, July 17, 2009 2:55 AM
Nimesh: You can select the table using $('#gdReports')
Comment posted by lavanya on Sunday, December 20, 2009 11:28 PM
very useful
Comment posted by Aleena Leon on Friday, April 16, 2010 9:01 AM
Will u help me to select more than one row at a time.

Thank U!
Comment posted by Nilay on Saturday, July 24, 2010 4:25 AM
Hey,pal....
thanks a lot for this post..
really amazing...
Comment posted by Mathieu Bazinet on Saturday, February 11, 2012 10:08 AM
Hi,

with:

if (GridView1.Rows.Count > 0)

        {

            GridView1.UseAccessibleHeader = true;            

            GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

            //GridView1.FooterRow.TableSection = TableRowSection.TableFooter;

        }

It generates the follwoing error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
[HttpException (0x80004005): The table  must contain row sections in order of header, body, then footer.]
   System.Web.UI.WebControls.Table.RenderContents(HtmlTextWriter writer) +8789469
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +32
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +10
   System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer, Boolean renderPanel) +238
   System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer) +33
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer) +173
   System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer) +31
   System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output) +53
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer) +40
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Control.Render(HtmlTextWriter writer) +10
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +208
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +8
   System.Web.UI.Page.Render(HtmlTextWriter writer) +29
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +100
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3060

Any idea why?

thanks

acheo
Comment posted by Simal on Tuesday, May 8, 2012 1:47 PM
Hi,
I have a asp gridview which has ADD button as a first column. I am beginners to JQUERY. The difficulty I am facing is when I clicked on ADD button, I have to add new row very next to the row which I clicked.
How to get clicked index using JQuery?
Comment posted by sadas on Tuesday, March 18, 2014 5:59 AM
adsadas
Comment posted by Vinay on Tuesday, June 17, 2014 7:11 AM
Nice article thanks

http://www.aspdotnet-pools.com/2014/06/highlight-gridview-row-on-mouseover.html