GridView lost sorting after paging?
<p>I got the below code from internet.It is working properly.I have added paging also.When I just sorting ,working properly.When I am changing the page index,looses sort.</p>

<p>//Client side</p>

<pre><code>&lt;asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False"
PageSize="20" AllowPaging="True" AllowSorting="True" 
OnSorting="GridView1_Sorting" CellPadding="4"&gt;
&lt;Columns&gt;
&lt;asp:TemplateField HeaderText="Employee no" SortExpression="eno"&gt;
&lt;ItemTemplate&gt;
&lt;%#Eval("eno")%&gt;
&lt;/ItemTemplate&gt;
&lt;/asp:TemplateField&gt;
&lt;asp:TemplateField HeaderText="Emp name" SortExpression="empname"&gt;
&lt;ItemTemplate&gt;
&lt;%#Eval("empname")%&gt;
&lt;/ItemTemplate&gt; 
&lt;/asp:TemplateField&gt;
&lt;asp:TemplateField HeaderText="Salary" SortExpression="sal"&gt;
&lt;ItemTemplate&gt;
&lt;%#Eval("sal")%&gt;
&lt;/ItemTemplate&gt; 
&lt;/asp:TemplateField&gt;
&lt;/Columns&gt;
&lt;/asp:GridView&gt;


//Server side

using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd;
SqlDataAdapter da;
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridData();
}
}
void GridData()
{
sqlcmd = new SqlCommand("select * from emp", sqlcon);
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count &gt; 0)
{
Session["dt"] = dt;
GridView1.DataSource = dt;
GridView1.DataBind();
} 
} 
private string GVSortDirection
{
get { return ViewState["SortDirection"] as string ?? "DESC"; }
set { ViewState["SortDirection"] = value; }
}
private string GetSortDirection()
{
switch (GVSortDirection)
{ 
case "ASC":
GVSortDirection = "DESC";
break;
assign new direction as ascending order
case "DESC":
GVSortDirection = "ASC";
break;
}
return GVSortDirection;
}

protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = (DataTable)Session["dt"];
if (dataTable != null)
{ 
DataView dataView = new DataView(dataTable); 
string sortDirection = GetSortDirection(); 
dataView.Sort = e.SortExpression + " " + sortDirection; 
GridView1.DataSource = dataView;
GridView1.DataBind();
}
} 
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridData();

}
}
</code></pre>
