Paging and Sorting in Gridview

Background

In this article we will learn about implementing paging and sorting in a GridView for displayinig many records in a GridView. So let us learn step-by-step so students can understand.
Step 1

Create Web Site as
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New" - "Project..." then select "C#" - "Empty Project" (to avoid adding a master page).
  3. Provide the project a name such as "GridPagingSorting" or another as you wish and specify the location.
  4. Then right-click on Solution Explorer rhen select "Add New Item" - "Default.aspx" page.
  5. Drag and Drop one GridView to the Default.aspx page. Then the page will look such as follows.
 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body bgcolor="silver">
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">
</asp:GridView>
</form>
</body>
</html>
 
Step 2

Create a function inside the Default.aspx.cs and call it Bindgrid to bind the GridView as in the following:
 
 Default.aspx.cs
 
  1. protected void Page_Load(object sender, EventArgs e)  
  2.     {  
  3.         if (!IsPostBack)  
  4.         {  
  5.             Bindgrid();  
  6.   
  7.         }  
  8.     }  
  9.     
  10.     private void Bindgrid()  
  11.     {  
  12.         connection();  
  13.         query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security  
  14.         com = new SqlCommand(query, con);  
  15.         SqlDataAdapter da = new SqlDataAdapter(com);  
  16.         dt = new DataTable();  
  17.         da.Fill(dt);  
  18.         ViewState["Paging"] = dt;  
  19.         GridView1.DataSource = dt;  
  20.         GridView1.DataBind();  
  21.         con.Close();  
  22.   
  23.     } 
Now run the application. Now the records in the GridView will be as:
 
 
 
Step 3

Now the GridView is filled in from the Database. Now first we implement paging in the GridView with the following procedure.
  • Set the AllowPaging property of the GridView control  to "true".
 
For example:
 <asp:GridView ID="GridView1" runat="server" AllowPaging="true" >
</asp:GridView>
  • Set the PageSize property of the GridView control to any number that specifies how many rows will be displayed in a GridView.
For example:
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="2" >
</asp:GridView> 
Now we need to call the one function on the OnPageIndexChanging event that is placed insdie the GridViewPageEventArgs event. The following is the code that we need to call:
 OnPageIndexChangin="Gridpaging"
  1. protected void Gridpaging(object sender, GridViewPageEventArgs e)  
  2.     {  
  3.         GridView1.PageIndex = e.NewPageIndex;  
  4.         GridView1.DataSource = ViewState["Paging"];  
  5.         GridView1.DataBind();  
  6.   
  7.   
  8.     } 
After calling the Gridpaging() function the GridView source code will look as in the following:
 
 <asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="2"  OnPageIndexChanging="Gridpaging" >
</asp:GridView>
 
 Now run the application; the paging will be as in the following:
 
 
 
In the preceding page we see that there are two rows displayed in the Gridview because we have set PageSize=2. Currently the paging is displayed in a number however we can also change it to an arrow button, images and so on.
 Step 4

Now next we will see about the sorting.
The default paging in a GridView is in ascending order, to allow sorting in a GridView we need to use the following events of the GridView:
  • AllowPaging="true"  that enables paging in the GridView.
  • OnSorting="sortingfunction"  that sorts the columns using a function called on the OnSorting event.

Create the following function that we call on the OnSorting event of the GridView.

  1. protected void Gridsorting(object sender, GridViewSortEventArgs e)    
  2.    {    
  3.        string ColumnTosort= e.SortExpression; //Reading the column name  
  4.     
  5.        if (CurrentSortDirection == SortDirection.Ascending)  //sorting in Descending if current sorting is Ascending order  
  6.        {    
  7.            CurrentSortDirection = SortDirection.Descending;    
  8.            SortGridView(ColumnTosort, DESCENDING);    
  9.        }    
  10.        else    
  11.        {    
  12.            CurrentSortDirection = SortDirection.Ascending;  //sorting in Ascending order if current sorting is Descending  
  13.            SortGridView(ColumnTosort, ASCENDING);    
  14.        }    
  15.     
  16.    }    
The preceding function is called on the OnSorting event that fires a GridViewSortEventArgs event and gives the current column name after clicking on the GridView column. We then sort by column checking the current sorting  and depending on that we sort the columns.

Now run the application; the default is ascending order, so the records will be displayed in the GridView as follows:
 
 
 
Now click on the address column of the GridView. The records will sort by Descending order as shown below because the current sorting is in ascending order.
 
 
 
Now from the example above we see how paging and sorting in a GridView is done, the entire code is as follows.
 
Default.aspx page
  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head runat="server">  
  3.     <title></title>  
  4. </head>  
  5. <body bgcolor="Silver">  
  6.     <form id="form1" runat="server">  
  7.      <br />  
  8.     <h4 style="color: #808000">  
  9.         Article by Vithal Wadje</h4>  
  10.     <br />  
  11.     <asp:ScriptManager ID="ScriptManager1" runat="server">  
  12.     </asp:ScriptManager>  
  13.     <asp:UpdatePanel ID="UpdatePanel1" runat="server">  
  14.     <ContentTemplate>  
  15.         <asp:GridView ID="GridView1" runat="server"  AllowSorting="true"  CellPadding="6" ForeColor="#333333"   
  16.             GridLines="None" PageSize="2" AllowPaging="true" OnPageIndexChanging="Gridpaging" OnSorting="Gridsorting">  
  17.             <AlternatingRowStyle BackColor="White" />  
  18.             <EditRowStyle BackColor="#7C6F57" />  
  19.             <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  20.             <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />  
  21.             <PagerSettings FirstPageText="First" LastPageText="End"   
  22.                 NextPageText="&gt;z" />  
  23.             <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />  
  24.             <RowStyle BackColor="#E3EAEB" />  
  25.             <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />  
  26.             <SortedAscendingCellStyle BackColor="#F8FAFA" />  
  27.             <SortedAscendingHeaderStyle BackColor="#246B61" />  
  28.             <SortedDescendingCellStyle BackColor="#D4DFE1" />  
  29.             <SortedDescendingHeaderStyle BackColor="#15524A" />  
  30.         </asp:GridView>   
  31.     </ContentTemplate>  
  32.     </asp:UpdatePanel>    
  33.     </form>  
  34. </body>  
  35. </html> 
 Default.aspx.cs Page
  1. using System;  
  2. using System.Configuration;  
  3. using System.Data.SqlClient;  
  4. using System.Web.UI.WebControls;  
  5. using System.Data;  
  6.   
  7. public partial class _Default : System.Web.UI.Page  
  8. {  
  9.     private SqlConnection con;  
  10.     private SqlCommand com;  
  11.     private string constr, query;  
  12.     private const string ASCENDING = " ASC";  
  13.     private const string DESCENDING = " DESC";  
  14.     DataTable dt;  
  15.     private void connection()  
  16.     {  
  17.         constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
  18.         con = new SqlConnection(constr);  
  19.         con.Open();  
  20.   
  21.     }  
  22.      
  23.     protected void Page_Load(object sender, EventArgs e)  
  24.     {  
  25.         if (!IsPostBack)  
  26.         {  
  27.             Bindgrid();  
  28.   
  29.         }  
  30.     }  
  31.     
  32.     private void Bindgrid()  
  33.     {  
  34.         connection();  
  35.         query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security  
  36.         com = new SqlCommand(query, con);  
  37.         SqlDataAdapter da = new SqlDataAdapter(com);  
  38.         dt = new DataTable();  
  39.         da.Fill(dt);  
  40.         ViewState["Paging"] = dt;  
  41.         GridView1.DataSource = dt;  
  42.         GridView1.DataBind();  
  43.         con.Close();  
  44.   
  45.     }  
  46.     protected void Gridpaging(object sender, GridViewPageEventArgs e)  
  47.     {  
  48.         GridView1.PageIndex = e.NewPageIndex;  
  49.         GridView1.DataSource = ViewState["Paging"];  
  50.         GridView1.DataBind();  
  51.   
  52.   
  53.     }  
  54.   
  55.     public SortDirection CurrentSortDirection  
  56.     {  
  57.         get  
  58.         {  
  59.             if (ViewState["sortDirection"] == null)  
  60.             {  
  61.                 ViewState["sortDirection"] = SortDirection.Ascending;  
  62.             }  
  63.   
  64.             return (SortDirection)ViewState["sortDirection"];  
  65.         }  
  66.         set  
  67.         {  
  68.             ViewState["sortDirection"] = value;  
  69.   
  70.         }  
  71.     }  
  72.     protected void Gridsorting(object sender, GridViewSortEventArgs e)  
  73.     {  
  74.         string ColumnTosort= e.SortExpression;  
  75.   
  76.         if (CurrentSortDirection == SortDirection.Ascending)  
  77.         {  
  78.             CurrentSortDirection = SortDirection.Descending;  
  79.             SortGridView(ColumnTosort, DESCENDING);  
  80.         }  
  81.         else  
  82.         {  
  83.             CurrentSortDirection = SortDirection.Ascending;  
  84.             SortGridView(ColumnTosort, ASCENDING);  
  85.         }  
  86.   
  87.     }  
  88.   
  89.     private void SortGridView(string sortExpression, string direction)  
  90.     {  
  91.         //  You can cache the DataTable for improving performance  
  92.         dynamic dt=ViewState["Paging"];  
  93.         DataTable dtsort = dt;       
  94.         DataView dv = new DataView(dtsort);  
  95.         dv.Sort = sortExpression + direction;  
  96.   
  97.         GridView1.DataSource = dv;  
  98.         GridView1.DataBind();  
  99.     }  

 Note
  • Download the Zip file from the attachment for the full source code of the application
  • Make changes in Web.config file as per your server location.
Summary

I hope this article is useful for all readers, if you have any suggestion then please contact me including beginners also.