Friday, February 18, 2011

GridView Sorting

protected void GridView_OnSorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dtSortTable = ViewState["CompanyData"] as DataTable;

        if (dtSortTable != null)
        {


            DataView dvSort = new DataView();
            dvSort = dtSortTable.DefaultView;
            //dtViewData is your data table - which in this case is loaded in teh function SearchControls
            string str = Convert.ToString(e.SortDirection);
            e.SortDirection = SortDirection.Ascending;

            ViewState.Add("SortCol", Convert.ToString(e.SortExpression));

            if (ViewState[e.SortExpression] != null)
            {
                if (Convert.ToString(ViewState[e.SortExpression]) == "Ascending")
                {
                    e.SortDirection = SortDirection.Descending;
                    ViewState[e.SortExpression] = "Desending";
                    dvSort.Sort = e.SortExpression + " DESC";
                }
                else
                {
                    e.SortDirection = SortDirection.Ascending;
                    ViewState[e.SortExpression] = "Ascending";
                    dvSort.Sort = e.SortExpression + " ASC";
                }
            }
            else
            {
                ViewState.Add(Convert.ToString(e.SortExpression), "Ascending");
                dvSort.Sort = e.SortExpression + " ASC";

            }

            GridView.DataSource = dvSort;
            GridView.DataBind();

        }
    }


No comments:

Post a Comment