Tuesday 13 August 2013

Gridview Sorting and Paging in asp.net C#

Design:

<asp:GridView ID="gdvRecords" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" PageSize="5" OnPageIndexChanging="gdvRecords_PageIndexChanging" AllowSorting="True" OnSorting="gdvRecords_Sorting">  </asp:GridView>





Paging:

     protected void gdvRecords_PageIndexChanging(object sender, GridViewPageEventArgs e)
     {
            GridView grdsample = (GridView)sender; //Get Current Gridview Object
            grdsample.PageIndex = e.NewPageIndex; //Set Page Index

            SqlConnection sqlcon = new SqlConnection(onnectionString);
            SqlCommand sqlcmdinsert = new SqlCommand("select * from Table",sqlcon);
            SqlDataAdapter sqlda = new SqlDataAdapter(sqlcmdinsert);         
            sqlda.Fill(dsAllData);
            gdvRecords.DataSource = dsAllData.Tables[0];
            gdvRecords.DataBind();
     }

Sorting:
   private const string ASCENDING = " ASC";
   private const string DESCENDING = " DESC";

   public SortDirection GridViewSortDirection
   {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

                return (SortDirection)ViewState["sortDirection"];
          }

            set { ViewState["sortDirection"] = value; }
   }


        private void SortGridView(string sortExpression, string direction)
        {
            DataTable dt;
            if (chkAll.Checked == true)
            {
                bindAllData();
                dt = dsAllData.Tables[0];
            }
            else
            {
                bindSearchData();
                dt = dsSearch.Tables[0];
            }
            //  You can cache the DataTable for improving performance
          

            DataView dv = new DataView(dt);
            dv.Sort = sortExpression + direction;

            gdvRecords.DataSource = dv;
            gdvRecords.DataBind();
        }

        protected void gdvRecords_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;

            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
            }
        }


No comments:

Post a Comment