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

Advertisements

One Response to “Paging and Sorting in GridView without using Datasource control”

  1. Aj Says:

    Very good!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: