You have to use the data source control with the GridView such as the SqlDataSource and ObjectDataSoure to enable sorting.
Otherwise you will have to write the code to enable sorting by yourself. Shown blow is sample:
.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class _0055_GridViewSorting : System.Web.UI.Page
{
// Create DataView as data source of GridView
protected DataView CreateDataSource()
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add(new DataColumn("ID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Name", typeof(string)));
dt.Columns.Add(new DataColumn("Type", typeof(string)));
dt.Columns.Add(new DataColumn("Price", typeof(Int32)));
dt.Columns.Add(new DataColumn("Qty", typeof(Int32)));
dt.Columns.Add(new DataColumn("Amount", typeof(Int32)));
dt.Columns.Add(new DataColumn("CatID", typeof(Int32)));
dt.Columns.Add(new DataColumn("Note", typeof(string)));
dt.Columns.Add(new DataColumn("Disc", typeof(bool)));
dt.Columns.Add(new DataColumn("Date", typeof(DateTime)));
for (int i = 0; i < 15; i++)
{
dr = dt.NewRow();
dr["ID"] = i;
dr["Name"] = "Product Name_" + i.ToString();
dr["Type"] = "Product Type " + (100 - i).ToString();
dr["Price"] = 123000 * (i + 1);
dr["Qty"] = (i + 1) * 20;
dr["Amount"] = 123000 * (i + 1) * (i + 1);
dr["CatID"] = 100 - i;
dr["Note"] = "Note_" + i.ToString();
dr["Disc"] = (i % 2 == 0) ? true : false;
dr["Date"] = DateTime.Now.AddDays(i);
dt.Rows.Add(dr);
}
return new DataView(dt);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = CreateDataSource();
GridView1.DataBind();
}
}
protected void GridView1_Sorting(object sender,
GridViewSortEventArgs e)
{
GridView gv = (GridView)sender;
DataView view = CreateDataSource();
string exp = e.SortExpression;
// switch ASC / DESC when same LinkButton is clicked
if (gv.Attributes["CurrentSortField"] != null &&
gv.Attributes["CurrentSortDir"] != null)
{
if (exp == gv.Attributes["CurrentSortField"])
{
if (gv.Attributes["CurrentSortDir"] == "ASC")
{
exp = exp + " DESC";
gv.Attributes["CurrentSortDir"] = "DESC";
}
else
{
exp = exp + " ASC";
gv.Attributes["CurrentSortDir"] = "ASC";
}
}
else
{
gv.Attributes["CurrentSortField"] = exp;
exp = exp + " ASC";
gv.Attributes["CurrentSortDir"] = "ASC";
}
}
view.Sort = exp;
gv.DataSource = view;
gv.DataBind();
}
}
.aspx
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="0055-GridViewSorting.aspx.cs"
Inherits="_0055_GridViewSorting" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server"
AllowSorting="True"
CurrentSortField=""
CurrentSortDir=""
onsorting="GridView1_Sorting">
</asp:GridView>
</form>
</body>
</html>
Result