DotNetCurry Logo

Some ASP.NET GridView UI Tips and Tricks using jQuery

Posted by: Suprotim Agarwal , on 1/19/2009, in Category jQuery and ASP.NET
Views: 962716
Abstract: This article demonstrates how to create simple UI effects in an ASP.NET GridView control using jQuery. These tips have been tested in IE 7 and Firefox 3.
Some ASP.NET GridView UI Tips and Tricks using jQuery
 
This article demonstrates how to create simple UI effects in an ASP.NET GridView control using jQuery. These tips have been tested in IE 7 and Firefox 3.
I assume you are familiar with jQuery. If not, please read my article over here before continuing any further: Using jQuery with ASP.NET - A Beginner's Guide. Update - A new version of jQuery has been released. jQuery 1.6.2 can be downloaded from over here: Download Query 1.6.2
You can also check out my new EBook on using jQuery with ASP.NET called "51 Tips, Tricks and Recipes with jQuery and ASP.NET Controls"
Set up an ASP.NET GridView as you usually do, binding it to a datasource. For demonstration purposes, here’s some sample markup where I am using the Northwind database and a GridView bound to the SQLDataSource to pull data from the database.
<form id="form1" runat="server">
<div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
        SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City] FROM [Customers]">
    </asp:SqlDataSource>   
    <br />          
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CustomerID"
        DataSourceID="SqlDataSource1" AllowPaging="False" 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>
</div>
</form>
The <connectionStrings> element in the web.config will look similar to the following:
      <connectionStrings>
            <add name="NorthwindConnectionString" connectionString="Data Source=(local);Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/>
      </connectionStrings>
Note: In most of the tips shown here, I am using a complex jQuery row ‘filter’ suggested by Karl Swedberg to a user in a jQuery forum. This filter is required due to the fact that a GridView does not render (accessibility tags) a <thead> and a <tfoot> by default(read this article of mine to learn how to make the GridView generate a <thead>). For the header, the GridView generates <th>’s inside <tr>. Similarly for the footer, the GridView generates a <table> inside a <tr> and so on. Hence it is required to use additional filters to exclude header and footer rows while adding UI effects on the GridView. These tips have been tried out on a GridView where paging is not enabled. When the paging is enabled, the pager however gets highlighted. I am still working on a solution to prevent the UI effects from being applied on the pager. I will update this article, once I find a solution. If you have a solution that works cross browser, please share it with me.
The link to download the code for all these samples can be found at the end of this article. Let’s see some tips.
1. Highlight an ASP.NET GridView row by clicking on it
This tip lets you highlight a row when you click anywhere on the row. Clicking back on a highlighted row, removes the highlight.
<head id="Head1" runat="server">
<title>Highlight Row on Click</title>
 
<script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
 
<script type="text/javascript">
    $(document).ready(function() {
        $("tr").filter(function() {
            return $('td', this).length && !$('table', this).length
        }).click(function() {
            $(this).toggleClass('currRow');
        });
    });
</script>
 
<style type="text/css">
    .currRow
    {
        background-color:Gray;
        cursor:pointer;
    }   
</style>
 
</head>
After applying the filter on the rows (to prevent the user from highlighting the Header and Footer row), we use the toggleClass to highlight/remove highlight on the row.
Output:
Tip 1 
2. Remove/Hide the Highlighted rows of an ASP.NET GridView
If you want to remove/hide the highlighted rows from the GridView, then here’s how to do so. I have added a HTML button control (Button1) to the form
<input id="Button1" type="button" value="Remove Rows" />
The jQuery is as shown below:
<head id="Head1" runat="server">
    <title>Hide Highlighted Rows>/title>
 
    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("tr").filter(function() {
                return $('td', this).length && !$('table', this).length
            }).click(function() {
                $(this).toggleClass('currRow');
            });
 
 
            $("#Button1").click(function() {               
                var hideRows = $("tr").hasClass("currRow");
                if (hideRows == true) {                   
                    $("tr.currRow").remove();
                }
            });
        });
       
    </script>
   
   
    <style type="text/css">
        .currRow
        {
            background-color:Gray;
            cursor:pointer;
        }   
    </style>
   
</head>
Here the user first highlights the rows and then clicks on the ‘Remove Rows’ button to remove the highlighted rows
 
3. Remove/Hide ASP.NET GridView Rows on Mouse Click
In our previous sample, we were following a two step process of first highlighting multiple rows and then removing them. Let’s say if we want to remove the rows as the user clicks on them, then follow this approach:
    <script type="text/javascript">
        $(document).ready(function() {
                $("tr").filter(function() {
                    return $('td', this).length && !$('table', this).length
                }).click(function() {
                    $(this).remove();
                });
        });       
    </script>
 
 
4. Highlight an ASP.NET GridView row on Mouse Hover
In case you do not want to define a separate style for the row and want to highlight a row on mouse over (instead of the click), follow this tip:
<head id="Head1" runat="server">
    <title>Highlight Row on Hover</title>
 
    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
   
    <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" }); }
                );
        });
    </script>
   
</head>
Output:
Tip 4 
5. Drag and Drop Rows of an ASP.NET GridView
This tip comes very handy when you are presenting a set of data in a GridView and want to rearrange rows at runtime. I am using the Table Drag and Drop Plugin for this example and it’s as simple as calling tableDnD() on the table. This plugin enables drag/drop on a table.
<head runat="server">
    <title>Drag Drop Rows</title>
 
    <script src="Scripts/jquery-1.3.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery.tablednd_0_5.js" type="text/javascript"></script>
   
    <script type="text/javascript">
        $(document).ready(function() {
            $("#GridView1").tableDnD();
        });
</script>
 
</head>
Output:
Before Drag
Tip 5 Before
After Drop - dragging row with Customer ID ‘ANATR’ below ‘BLONP’
Tip 5 After
That’s it for now. We saw some UI tips that can be applied to an ASP.NET GridView using jQuery. Stay tuned to see some more in the forthcoming articles. I am also planning to write an article to store these UI changes when the user paginates through the Grid or a postback occurs.
I hope you liked the article and I thank you for viewing it. The entire source code of this article can be downloaded from here. 
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
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 a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Martin on Wednesday, February 4, 2009 12:13 PM
When will you post something that will explain saving the UI changes? Otherwise, as you noted it's kind of useless. Also, can you do drag and drop with a nested gridview or a treeview?
Comment posted by Suprotim Agarwal on Friday, February 6, 2009 2:30 AM
Martin: I can't commit on a date, but i plan to do it soon.
Comment posted by san on Saturday, February 14, 2009 3:31 AM
can you please also show code for remove columns of gridview ?
thanks in advance
Comment posted by Arun on Tuesday, April 7, 2009 4:35 PM
Very helpful to me
Comment posted by daVC on Wednesday, April 8, 2009 4:50 AM
You are my Jquery Mentor. that is a very nice post
Thanks.
Comment posted by Jim on Wednesday, April 8, 2009 6:40 AM
Nice articel. One of the problems I have experienced with this tenique is that you are using the <tr> tag as the locator. This not only works on the Gridview which is sent to the browser as a table - but also on as asp.net menu control - alsoo sent as a table - or in fact - any html table that you may have placed on the page.
We need a way to select by ID.
Comment posted by Ahmed on Wednesday, April 8, 2009 11:03 AM
Great
Comment posted by Suprotim Agarwal on Wednesday, April 8, 2009 12:15 PM
Jim - Did you try $('tr','#GridView1').filter

Arun,daVC,Ahmed:  Thanks!
Comment posted by David on Thursday, April 9, 2009 5:44 AM
Why do you keep  putting the following in your JQuery?

$("tr").filter(function() {
    return $('td', this).length && !$('table', this).length
})

Is it to stop clicks/hovers appearing on the header/footer? If so you can just use

$("tbody tr")

You will have problems accessing GridViews by ID using $("#GridView1") as GridView1 may not be the client id, I would use a class instead eg $(".grid")
Comment posted by Suprotim Agarwal on Thursday, April 9, 2009 7:41 PM
David: - Good point. I use a class everytime but in a hurry it seems, I used the ID. I do remember trying the $("tbody tr") but does it prevent highlighting the footer row (since tfoot is not generated)? I will have to check.
Comment posted by Ming on Thursday, April 16, 2009 3:14 AM
Great Article! Great for beginner who want to learn ASP.NET + jQuery!!
Comment posted by anup hosur on Friday, May 8, 2009 2:57 AM
great article.. But i really liked ur five post on this..
Comment posted by varun2050 on Monday, May 18, 2009 7:55 AM
Sir i have downloaded one code file which has the password.what is the password?
Comment posted by .net development on Friday, June 26, 2009 3:17 AM
Great Tips! Really i enjoyed this post very well. Thanks for sharing.
Comment posted by RK on Wednesday, July 8, 2009 7:31 AM
Good article
Comment posted by marv100 on Thursday, July 9, 2009 5:03 AM
nice article. i try drag&drop function in my Gridview. it works but i can't save my changes. can anybody help me?
Comment posted by RV on Tuesday, August 11, 2009 4:27 AM
Nice article...
Comment posted by Crystal on Friday, August 28, 2009 12:44 PM
interesting info at this post thanks!!i really like it

<a href="http://www.belle-naturelle.net/" title="">Spa Treatments</a>
Comment posted by Akhil Gupta on Wednesday, October 28, 2009 1:43 AM
Sir...article was excellent...but i was unable to donnload query1.3,so please write me how i will get it to my mail.
Thanks.
Comment posted by Maldito on Thursday, November 5, 2009 1:14 PM
Thanks for writing the article. I wish you showed an example that does the mousehover, mouseout and click in one page but I'm still thankful for this.
Comment posted by Snaga on Tuesday, November 17, 2009 10:15 AM
thnx for this article, it really helped me
for hovering over rows/header/footer you can add property for gridview in aspx page
RowStyle-CssClass="testing"

and then just add this code
<script type="text/javascript">

$(document).ready(function(){
$(".testing")
            .live("mouseover", function() { $(this).addClass('hover'); })
            .live("mouseout", function() { $(this).removeClass('hover');});
         });
</script>

(hover class holds background-color)

and that's it for hovering effect over rows in gridview, to get the hover effect for
Header or footer just add classes for HeaderStyle-CssClass and FooterStyle-CssClass

cheers
Comment posted by Snaga on Wednesday, November 18, 2009 3:26 AM
thnx for this article, it really helped me
for hovering over rows/header/footer you can add property for gridview in aspx page
RowStyle-CssClass="testing"

and then just add this code
<script type="text/javascript">

$(document).ready(function(){
$(".testing")
            .live("mouseover", function() { $(this).addClass('hover'); })
            .live("mouseout", function() { $(this).removeClass('hover');});
         });
</script>

(hover class holds background-color)

and that's it for hovering effect over rows in gridview, to get the hover effect for
Header or footer just add classes for HeaderStyle-CssClass and FooterStyle-CssClass

cheers
Comment posted by vallab on Friday, November 20, 2009 1:32 AM
Excellent article. I got the basic idea from it. But still my footer getting highlighted and i tried the above code..<script type="text/javascript">

$(document).ready(function(){
$(".testing")
            .live("mouseover", function() { $(this).addClass('hover'); })
            .live("mouseout", function() { $(this).removeClass('hover');});
         });
</script>

still it doesnot work for me.Also my css class not getting attach to the function.

Help to sort this out.
1. Prevent footer to highlight.
2. Add class instead of background color.
or if possible getting the original color of the row and reassign on exit.
Comment posted by glen on Thursday, May 27, 2010 12:05 PM
Hi great article.
Do you know or does anyone else know how I can save these UI changes back to my DB?
Thanks
Comment posted by amit on Tuesday, September 28, 2010 1:06 PM
thanks
Comment posted by Jonathan on Monday, January 17, 2011 10:03 PM
highlight gridview rows without highlighting the pager. Works for me when using the default paging controls, not sure about with custom paging controls

$("#grid_id tr:not(tr:last-child)").filter(function () {
            return $('td', this).length && !('table', this).length
        }).hover(function () {
            $(this).toggleClass('hover_css');
        });
Comment posted by Baha on Saturday, January 29, 2011 3:53 PM
Thank you, Thank you, Thank you , Thank you
Comment posted by praneeth on Wednesday, March 2, 2011 11:17 PM
awesome article
Comment posted by MSK on Saturday, June 18, 2011 6:15 AM
It's good
Comment posted by Kelvin on Sunday, August 28, 2011 3:53 AM
Thanks! Awesome article.
In Drag and Drop Rows of an ASP.NET GridView,
any idea to save the record after drag and drop?
Comment posted by Somesh Batra on Thursday, January 5, 2012 8:29 AM
Very informative post. It's really helpful for me and helped me lot to complete my task.

Thanks for sharing with us. I had found another nice post over the internet which was

also explained very well about GridView Decoration in ASP.Net, for

more details of this post check out this link...

http://mindstick.com/Articles/0efe2da6-407e-4442-a675-475bd6f8a2d7/?GridView%20Decoration%20in%20ASP.Net

Thanks
Comment posted by Mark on Wednesday, February 1, 2012 11:09 AM
Instead of allowing multiple rows to be highlighted, how would you make to allow on one row to be highlighted, in other words other rows are cleared before highlighting the selected row...Thanks
Comment posted by subham on Thursday, February 16, 2012 4:49 AM
hi,
How can i refresh my gird through jquery
Comment posted by Virendra Dugar on Monday, April 23, 2012 5:39 AM
This site also has some great GridView tips and tricks with jQuery. http://jquerybyexample.blogspot.com/search/label/GridView
Comment posted by sfs on Monday, August 13, 2012 7:49 AM
dfs
Comment posted by dwd on Thursday, January 24, 2013 10:11 PM
mental
Comment posted by Sam on Thursday, July 25, 2013 5:33 PM
can anyone suggest how to make the columns editable.
Comment posted by Himanshu Kamothi on Tuesday, March 25, 2014 1:23 AM
Last trick about drag-drop rows of grid view:
Give me suggestion to trigger database at the time of drop row.