Many of the data controls used by ASP.NET support built-in table sorting but they use a lot of resources. Even using the ASP.NET AJAX controls and UpdatePanels can be a little clumsy.
A better solution is to use the jQuery plugin tablesorter. Here are a couple of examples on how to use this plugin with both a Gridview and a Listview.
First, here is a working demo of the code below.
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
'By default the gridview does not include the <thead> and <tbody> tags
Sub grdMovies_PreRender(ByVal sender As Object, ByVal e As EventArgs)
If grdMovies.Rows.Count > 0 Then
grdMovies.UseAccessibleHeader = True
'Adding the <thead> and <tbody> elements
grdMovies.HeaderRow.TableSection = TableRowSection.TableHeader
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Table Sorter</title>
<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="jquery/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
// make the Listview table sortable
$("#moviesTable").tablesorter();
// make the Gridview table sortable
$("#grdMovies").tablesorter();
});
</script>
</head>
<body>
<form runat="server" id="form1">
<asp:SqlDataSource
id="srcMovies"
ConnectionString="<%$ ConnectionStrings:xxxxx %>"
SelectCommand="SELECT Id,Title,Director FROM Movies"
Runat="server" />
<h3>Using a Listview</h3>
<asp:ListView ID="lstMovies" DataSourceID="srcMovies" runat="server">
<LayoutTemplate>
<table id="moviesTable">
<thead>
<tr>
<th title="Sort by Id">Id</th>
<th title="Sort by Title">Title</th>
<th title="Sort by Director">Director</th>
</tr>
</thead>
<tbody>
<asp:PlaceHolder ID="ItemPlaceholder" runat="server" />
</tbody>
</table>
</LayoutTemplate>
<ItemTemplate>
<tr>
<td><%# Eval("Id") %></td>
<td><%# Eval("Title")%></td>
<td><%# Eval("Director")%></td>
</tr>
</ItemTemplate>
</asp:ListView>
<h3>Using a Gridview</h3>
<asp:GridView
id="grdMovies"
DataSourceID="srcMovies"
DataKeyNames="Id"
OnPreRender="grdMovies_PreRender"
Runat="server" />
</form>
</body>
</html>