Friday, September 10, 2010

Manually sorting and paging Gridview without using datasource control

Many a times while working with Gridview we want to work with the paging and sorting functionality without using any datasource control. Gridview is flexible enough to perform these tasks without the use of any datasource control and only a few lines of code.  
For paging a Gridview manually we have to handle the Gridview’s PageIndexChanged Event.  In the event we need to change the PageIndex of Gridview to the page that user has clicked and again bind the Gridview.
protected void gvPaging_PageIndexChanging(object sender, GridViewPageEventArgs e)
   gvPaging.PageIndex = e.NewPageIndex;

This is all you need to do to make manual paging in the Gridview.
For manually sorting in Gridview we need to handle the Sorting event of Gridview. Here is the code to do it.
protected void gvSorting_Sorting(object sender, GridViewSortEventArgs e)
   DataTable dtSortTable = gvSorting.DataSource as DataTable;
   if (dtSortTable != null)
      DataView dvSortedView = new DataView(dtSortTable);
     dvSortedView.Sort = e.SortExpression + " " + getSortDirectionString(e.SortDirection);
      gvSorting.DataSource = dvSortedView;