GridView Sorting

Step 1 :Create a New WebPage

Step 2 : Add a GridView Control into your Page.

       < asp :GridView ID="GridView1" runat="server">
        < / asp :GridView >


Step 3 : Set the AllowSorting property as True in GridView

      < asp :GridView ID="GridView1" runat="server" AllowSorting="True" >
        < / asp :GridView >

Step 4 : Add the Namespaces as

using System.Data;
using System.Data.SqlClient;

Step 5 : In page_Load Event Call the GridView Binding Fuction.

Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridInfo();
}
}

BindGridInfo Function
static SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
static SqlCommand cmd = new SqlCommand();

void BindGridInfo()
{
try
{
con.Open();
cmd = new SqlCommand("SQL select Query", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ViewState["GridData"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
ViewState["sort"] = " ASC";
}
catch (Exception ex) { Response.Write(ex.Message); }
finally { con.Close(); cmd.Dispose(); }
}

Step 6 : Add the Sorting Event to GridView

        < asp :GridView ID="GridView1" runat="server" AllowSorting="True"
            onsorting="GridView1_Sorting">
        < /asp :GridView >

Step 7 : In the Sorting Event add the Code as

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
if (ViewState["GridData"] != null)
{
DataView dv = new DataView((DataTable)ViewState["GridData"]);
if (ViewState["sort"].ToString() == " ASC") { ViewState["sort"] = " DESC"; }
else { ViewState["sort"] = " ASC"; }
dv.Sort = e.SortExpression.ToString() + ViewState["sort"];
GridView1.DataSource = dv;
GridView1.DataBind();
}
}

Now Press F5.