Coloum value Sorting in Gridview

Hi,
 Here i will code you how to sort the data in the Gridview to Ascending and Descending order, To use this functionality you should enable Allow Sorting to true in Gridview Properties. OnSorting event will be used to sort the data Accordingly.Sorting can be used for Numeric values,Alphabetical values also even for dates.


Aspx code : 

<html>
<head runat="server">
 <title>Coloum value sorting in Gridview</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="grd_popup_details" HeaderStyle-BackColor="#cccccc" runat="server" AllowSorting="true" OnSorting="SortingEvent">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

C# Code : 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace TTip
{
    public partial class ttcss : System.Web.UI.Page
    {
        DataSet DS = new DataSet();
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("connection string");
            string Query = "select Query";
            SqlDataAdapter da = new SqlDataAdapter(Query, con);
            con.Open();
            da.Fill(DS);
            grd_popup_details.DataSource = DS;
            grd_popup_details.DataBind();
            con.Close();
        }

        protected void SortingEvent(object sender, GridViewSortEventArgs e)
        {
            string sortDirection = "ASC";
            DataView dataView = new DataView(DS.Tables[0]);
            DataSet Ds_Sort = new DataSet();
            if (ViewState["sortkeyGV1"] != null)
            {
                if (ViewState["sortkeyGV1"].ToString() == e.SortExpression)
                    sortDirection = "DESC";
            }
            dataView.Sort = e.SortExpression + " " + sortDirection;
            Ds_Sort.Tables.Add(dataView.ToTable());

            grd_popup_details.DataSource = Ds_Sort;
            grd_popup_details.DataBind();
            ViewState["sortkeyGV1"] = e.SortExpression;
        }
    }
}