Paging and Sorting in Gridview

Background

In this article, we will learn about implementing paging and sorting in a GridView for displaying 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.
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5. <title></title>  
  6. </head>  
  7. <body bgcolor="silver">  
  8. <form id="form1" runat="server">  
  9. <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None">  
  10. </asp:GridView>  
  11. </form>  
  12. </body>  
  13. </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. private void Bindgrid()    
  10. {    
  11.     connection();    
  12.     query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security    
  13.     com = new SqlCommand(query, con);    
  14.     SqlDataAdapter da = new SqlDataAdapter(com);    
  15.     dt = new DataTable();    
  16.     da.Fill(dt);    
  17.     ViewState["Paging"] = dt;    
  18.     GridView1.DataSource = dt;    
  19.     GridView1.DataBind();    
  20.     con.Close();    
  21. } 
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:
  1. <asp:GridView ID="GridView1" runat="server" AllowPaging="true" >  
  2. </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:
  1. <asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="2" >  
  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. }
After calling the Gridpaging() function the GridView source code will look as in the following:
  1. <asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="2"  OnPageIndexChanging="Gridpaging" >  
  2. </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. } 
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=">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.     private void Bindgrid()    
  32.     {    
  33.         connection();    
  34.         query = "select *from Employee";//not recommended this i have written just for example,write stored procedure for security    
  35.         com = new SqlCommand(query, con);    
  36.         SqlDataAdapter da = new SqlDataAdapter(com);    
  37.         dt = new DataTable();    
  38.         da.Fill(dt);    
  39.         ViewState["Paging"] = dt;    
  40.         GridView1.DataSource = dt;    
  41.         GridView1.DataBind();    
  42.         con.Close();  
  43.     }    
  44.     protected void Gridpaging(object sender, GridViewPageEventArgs e)    
  45.     {    
  46.         GridView1.PageIndex = e.NewPageIndex;    
  47.         GridView1.DataSource = ViewState["Paging"];    
  48.         GridView1.DataBind();  
  49.     }    
  50.     
  51.     public SortDirection CurrentSortDirection    
  52.     {    
  53.         get    
  54.         {    
  55.             if (ViewState["sortDirection"] == null)    
  56.             {    
  57.                 ViewState["sortDirection"] = SortDirection.Ascending;    
  58.             }  
  59.             return (SortDirection)ViewState["sortDirection"];    
  60.         }    
  61.         set    
  62.         {    
  63.             ViewState["sortDirection"] = value;    
  64.         }    
  65.     }    
  66.     protected void Gridsorting(object sender, GridViewSortEventArgs e)    
  67.     {    
  68.         string ColumnTosort= e.SortExpression;    
  69.     
  70.         if (CurrentSortDirection == SortDirection.Ascending)    
  71.         {    
  72.             CurrentSortDirection = SortDirection.Descending;    
  73.             SortGridView(ColumnTosort, DESCENDING);    
  74.         }    
  75.         else    
  76.         {    
  77.             CurrentSortDirection = SortDirection.Ascending;    
  78.             SortGridView(ColumnTosort, ASCENDING);    
  79.         }    
  80.     
  81.     }    
  82.     
  83.     private void SortGridView(string sortExpression, string direction)    
  84.     {    
  85.         //  You can cache the DataTable for improving performance    
  86.         dynamic dt=ViewState["Paging"];    
  87.         DataTable dtsort = dt;         
  88.         DataView dv = new DataView(dtsort);    
  89.         dv.Sort = sortExpression + direction;    
  90.     
  91.         GridView1.DataSource = dv;    
  92.         GridView1.DataBind();    
  93.     }    
  94. }   
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.


Similar Articles