scadassarse
New Member
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.//Client side\[code\]<asp:GridView ID="GridView1" runat="server" DataKeyNames="eno" AutoGenerateColumns="False"PageSize="20" AllowPaging="True" AllowSorting="True" OnSorting="GridView1_Sorting" CellPadding="4"><Columns><asp:TemplateField HeaderText="Employee no" SortExpression="eno"><ItemTemplate><%#Eval("eno")%></ItemTemplate></asp:TemplateField><asp:TemplateField HeaderText="Emp name" SortExpression="empname"><ItemTemplate><%#Eval("empname")%></ItemTemplate> </asp:TemplateField><asp:TemplateField HeaderText="Salary" SortExpression="sal"><ItemTemplate><%#Eval("sal")%></ItemTemplate> </asp:TemplateField></Columns></asp:GridView>//Server sideusing 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 > 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 ordercase "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\]