Paging and Sorting in GridView without using Datasource control

Paging and Sorting in Gridview can be enabled in an ASP.NET by handling the PageIndexChanging and Sorting events of the Gridview

ASP.NET

 

In the web page add the gridview from the toolbox

<asp:GridView
ID=”gridView”
OnPageIndexChanging=”gridView_PageIndexChanging” 

OnSorting=”gridView_Sorting”
runat=”server” />

 

Code Behind

 

I have a function ConvertSortDirection to display the direction of sort.

private string ConvertSortDirection(SortDirection sortDireciton)
{
   string newSortDirection = String.Empty;

   switch (sortDirection)
   {
      case
SortDirection.Ascending:
         newSortDirection = “ASC”;
         break;

      case
SortDirection.Descending:
         newSortDirection = “DESC”;
         break;
   }

   return newSortDirection
}

 

PageIndexChanging

 

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
   gridView.PageIndex = e.NewPageIndex;
   gridView.DataBind();
}

 

Sorting

protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
   DataTable dataTable = gridView.DataSource as
DataTable;

   if (dataTable != null)
   {
      DataView dataView = new
DataView(dataTable);
      dataView.Sort = e.SortExpression + ” “ + ConvertSortDirectionToSql(e.SortDirection);

      gridView.DataSource = dataView;
      gridView.DataBind();
   }
}

 

Happy coding J