Monday, 14 November 2011

SORTING AND PAGING IN A GRIDVIEW

 To manually allow paging and sorting  in a gridview, include
AllowSorting="True" AllowPaging="True" onpageindexchanging="GridView1_PageIndexChanging" onsorting="GridView1_Sorting" in the gridview control.

The code behind is,

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
           
            GridView1.PageIndex = e.NewPageIndex;
            GridView1.DataBind();
            //Bindgrid();
        }

        protected void GridView1_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);
            }
        }

        private void SortGridView(string sortExpression, string direction)
        {
            //  You can cache the DataTable for improving performance
            SqlConnection con = new SqlConnection(connection);
            con.Open();
            DA = new SqlDataAdapter("Select * from table_name", con);
            DataTable dt = new DataTable();
            DA.Fill(dt);

            GridView1.DataSource = dt;
            GridView1.DataBind();
            con.Close();

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

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

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

                return (SortDirection)ViewState["sortDirection"];
            }
            set { ViewState["sortDirection"] = value; }
        }

No comments:

Post a Comment