Grid View Columns Sorting Example

In GridView-Sorting.aspx file

<asp:GridView ID="gvstudents" EnableViewState="false" runat="server" AllowSorting="true" 
    OnSorting="gvstudents_sorting">
    </asp:GridView>

In GridView_sorting.aspx.cs

public partial class SortingEx : System.Web.UI.Page
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            string strcon = "data source=ADMIN-PC\\SQLEXPRESS;initial catalog=db24_25;integrated security=sspi";
            string sConnection = strcon;
            DataSet ds = new DataSet();
            SqlConnection cn = new SqlConnection(sConnection);
            using (cn)
            {
                SqlCommand cmd = new SqlCommand("select * from employees", cn);
                using (cmd)
                {
                    SqlDataAdapter da = new SqlDataAdapter();
                    da.SelectCommand = cmd;
                    da.Fill(ds);
                    gvstudents.DataSource = ds;
                    gvstudents.DataBind();
                    Session["ds"] = ds;
                    ViewState["sortcolumn"] = string.Empty;
                    ViewState["sortdirection"] = string.Empty;
                }
                //string s=cmd.CommandText;
            }
            //cn.Open();
        }
    }
    protected void gvstudents_sorting(object sender, GridViewSortEventArgs e)
    {
        if (Session["ds"] != null)
        {
           DataSet ds = (DataSet)Session["ds"];
           DataTable dt = ds.Tables[0];
           DataView dv = dt.DefaultView;//DataView ado.net view in t-sql 
            if (ViewState["sortcolumn"].ToString() == e.SortExpression.ToString())
            {
                if ("asc" == ViewState["sortdirection"].ToString())
                {
                    ViewState["sortdirection"] = "DESC";
                }
                else
                {
                    ViewState["sortdirection"] = "asc";
                }
            }
            else
            {
                ViewState["sortcolumn"] = e.SortExpression.ToString();
                ViewState["sortdirection"] = "asc";
            }
            if (dv != null)
            {
                dv.Sort = e.SortExpression + " " + ViewState["sortdirection"].ToString();
                //dv.Sort= "ename asc";
                gvstudents.DataSource = dv;
                gvstudents.DataBind();
            }
        }

    }
}

Required Table:

Employees table