You can use a DataView object to create a sortable, filterable view of a DataTable.
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void Page_Load()
{
if (Session["ProductsToSort"] == null)
{
string connectionString = WebConfigurationManager.ConnectionStrings["Products"].ConnectionString;
SqlDataAdapter dad = new SqlDataAdapter("SELECT Id,Title,Director FROM Products", connectionString);
DataTable dtblProducts = new DataTable();
dad.Fill(dtblProducts);
Session["ProductsToSort"] = dtblProducts.DefaultView;
}
if (!Page.IsPostBack)
BindProducts();
}
void BindProducts()
{
grdProducts.DataSource = Session["ProductsToSort"];
grdProducts.DataBind();
}
protected void grdProducts_Sorting(object sender, GridViewSortEventArgs e)
{
DataView dvwProducts = (DataView)Session["ProductsToSort"];
dvwProducts.Sort = e.SortExpression;
BindProducts();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
<title>Show DataView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView
id="grdProducts"
AllowSorting="true"
OnSorting="grdProducts_Sorting"
Runat="server" />
</div>
</form>
</body>
</html>
File: Web.config
<configuration>
<connectionStrings>
<add name="Products"
connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|MyDatabase.mdf;Integrated Security=True;User Instance=True" />
</connectionStrings>
</configuration>
|