Saturday, December 21, 2013

ASP.NET GridView sorting

Here will explains how to enable sorting on ASP.NET Grid View control. Following are key things that you have to remember when you are enabling sorting in Grid View control.

Here is the Demo Solution
  • Give SortExpression to the columns that you need to sort in grid view.
  • AllowSorting="true" in grid view markup.
  • Create event for "OnSorting" in gridview.
Here is the markup of the GridView.



Code Behind

This is where you convert you data to DataView and assign sorting expression to the DataView and bind the data to the GridView.

As an example sortExpression is like "Id ASC";

private void BindStudents(string sortExpression)
{
            //Get student data as list and convert it to the datatable
            DataTable studentsDt = GetStudents().ToDataTable();
            DataView studentDataView = new DataView(studentsDt);
            studentDataView.Sort = sortExpression;
            StudentGridView.DataSource = studentDataView;
            StudentGridView.DataBind();
}

Then each time you need to keep the track of the current sorting direction("ASC or DESC"). Therefore I have used ViewState to keep track of it.

public string SortingDirection
{
            get { return ViewState[expressionViewStateKey] as string ?? asendingOrder; }
            set { ViewState[expressionViewStateKey] = value; }
}

Then implement the OnSorting event to generate new sorting expression and rebind the data to the gridview.

protected void StudentGridView_Sorting(object sender, GridViewSortEventArgs e)
{
            //Toggle sorting directions according to the current sorting direction
            if (SortingDirection == "ASC")
                SortingDirection = "DESC";
            else
                SortingDirection = "ASC";

            string sortExpression = string.Format(CultureInfo.InvariantCulture, "{0} {1}",
                                                                    e.SortExpression, SortingDirection);
             //Rebind data to the gridview with new soring expression
             BindStudents(sortExpression);

}

No comments:

Post a Comment