Home > Articles > ASP.NET Articles > How to implement paging and sorting in asp.net Gridview control?

How to implement paging and sorting in asp.net Gridview control?

by Thamil   on Jun 28, 2013   Category: ASP.NET  | Level: Intermediate  |  Views: 142939    |  Points: 100   
Like this article? Bookmark and Share:
In this article, I will explore how to implement paging and sorting in gridview control without using sql and object data sources.

 

Introduction


In general, we often use paging and sorting feature in gridview control for all asp.net projects.  Suppose if you want to display large amount records in gridview, we use paging and display set of few records in each gridview pages. Sorting feature used to sort the records based on the selected columns in gridview and display the records in ascending or descending order. There are many ways, we can achieve this and below is one of the way. Here I’m explaining this feature without using sql and object data sources.

Step 1: Create new asp.net project

First create a new asp.net project and open web.config file then add database connection string as shown below. Before this setup, prepare database and sample table to display records in gridview.

<connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=TEST\SQLEXPRESS;Initial Catalog=TEST_DB;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>

 

Step 2: Design aspx page

Then add a new aspx page and format the gridview as like below- copy and place below code in aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="gridviewSortPaging.aspx.cs"
    Inherits="GridviewPagingSorting._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>Gridview Paging and Sorting </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div style="font-size: 20px; font-family: Verdana">
           <u> Gridview Paging and Sorting</u>
            <br />
            <br />
        </div>
        <div>
            <asp:GridView ID="GridVwPagingSorting" runat="server" AutoGenerateColumns="False"
                Font-Names="Verdana" AllowPaging="True" AllowSorting="True" PageSize="5" Width="75%"
                OnPageIndexChanging="PageIndexChanging" BorderColor="#CCCCCC" BorderStyle="Solid"
                BorderWidth="1px" OnSorting="Sorting">
                <AlternatingRowStyle BackColor="#BFE4FF" />
                <PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
                <HeaderStyle Height="30px" BackColor="#6DC2FF" Font-Size="15px" BorderColor="#CCCCCC"
                    BorderStyle="Solid" BorderWidth="1px" />
                <RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
                    BorderWidth="1px" />
                <Columns>
                    <asp:BoundField DataField="Emp_Name" HeaderText="Employee Name" SortExpression="Emp_Name" />
                    <asp:BoundField DataField="Emp_id" HeaderText="Employee ID" SortExpression="Emp_id" />
                    <asp:BoundField DataField="Emp_job" HeaderText="Job title" SortExpression="Emp_job" />
                    <asp:BoundField DataField="Emp_Dep" HeaderText="Department" SortExpression="Emp_Dep" />
                </Columns>
            </asp:GridView>
        </div>
        <div style="color: Green; font-weight: bold">
            <br />
            <i>You are viewing page
                <%=GridVwPagingSorting.PageIndex + 1%>
                of
                <%=GridVwPagingSorting.PageCount%>
            </i>
        </div>
    </div>
    </form>
</body>
</html>
 

 

For paging and sorting in gridview, we need to set Allowpaging  and Allowsorting property as true and autogenerate column must be false. Create the event OnPageIndexChanging for paging and sorting event for sorting.

Step 3: Code behind part

In the code behind part we have 3 events such as page load, OnPageIndexChanging and sorting event and Getdata function will be used to get the data from database and load into gridview. Copy the below code and place into code behind area.

Namespace used:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

 

        string Sort_Direction = "Emp_Name ASC";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                  ViewState["SortExpr"] = Sort_Direction;
                  DataView dvEmployee = Getdata();
                  GridVwPagingSorting.DataSource = dvEmployee;
                  GridVwPagingSorting.DataBind();
            }
        }
private DataView Getdata()
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ToString()))
            {
                DataSet dsEmployee = new DataSet();
                string strSelectCmd = "SELECT [Emp_Name],[Emp_id],[Emp_job],[Emp_Dep],[Emp_Salary] FROM [employee]";
                SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, conn);
                da.Fill(dsEmployee, "Employee");
                DataView dvEmp = dsEmployee.Tables["Employee"].DefaultView;
                dvEmp.Sort = ViewState["SortExpr"].ToString();
                return dvEmp;   
            }
        }
 

Using above page load event,retrieve the data from database table and load into dataview for customize(sort) the data in specific order (asc) for the first Employee name column and binding into gridview. Once complete this above part and execute the project then page will display as like below

protected void PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridVwPagingSorting.PageIndex = e.NewPageIndex;
            DataView dvEmployee = Getdata();
            GridVwPagingSorting.DataSource = dvEmployee;
            GridVwPagingSorting.DataBind();
        }

 

The above PageIndexChanging event will be used to change gridview page index. NewPageIndex will return the index of next page and assign into gridview pageindex property and again bind gridview with datasource. Once done this part the paging will work as like below

Above I’m displaying the total pages and current display page using gridvew pageindex and Pagecount properties. You will see the below code in aspx page.

<div style="color: Green; font-weight: bold">
            <br />
            <i>You are viewing page
                <%=GridVwPagingSorting.PageIndex + 1%>
                of
                <%=GridVwPagingSorting.PageCount%>
            </i>
</div>

 

protected void Sorting(object sender, GridViewSortEventArgs e)
        {
            string[] SortOrder = ViewState["SortExpr"].ToString().Split(' ');
            if (SortOrder[0] == e.SortExpression)
            {
                if (SortOrder[1] == "ASC")
                {
                    ViewState["SortExpr"] = e.SortExpression + " " + "DESC";
                }
                else
                {
                    ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
                }
            }
            else
            {
                ViewState["SortExpr"] = e.SortExpression + " " + "ASC";
            }
            GridVwPagingSorting.DataSource = Getdata();
            GridVwPagingSorting.DataBind();
        }

Above sorting event will be used to sort the selected column in ascending or descending order. This event will occur when clicks on the gridview header hyperlink. To do the sorting, first get existing sorting column and order and change the sorting order accordingly. If user clicked same column header then change only sort order else add clicked column and ascending as sorting order in sorting expression. Here we are storing the sorting order in view state because after post back we need to get previous sorting details from this view state and change new order accordingly. Below screen displays the records in descending order after clicking Employee Name column.

I have attached the sample demo project with this article, download this demo project and see how it’s working.
Thanks for reading. I hope this will help you to understand how to implement paging and sorting in gridview control. Please provide your feedback and suggestions below.

 



Like this article? Bookmark and Share:

Most viewed Articles

User Comments


  Re :How to implement paging and sorting in asp.net Gridview control?   
Posted by Preethika Rajendran
on 12/1/2013 1:59:42 AM
Points : 10

Very helpful. Thanks a lot.
  Re :How to implement paging and sorting in asp.net Gridview control?   
Posted by Rajaraman S
on 1/13/2014 7:09:08 AM
Points : 10

I have three questions here:

1) How will you set and where are you setting GridVwPagingSorting.PageCount?
2) This looks like you are getting all the records from database on the client side and then do a pagination as I couldn't find sending the count for a page. Don't you think it will be so memory intensive?
3) How will you set the PageNumbers on the Grid below like 1,2,3 etc..

Otherwise, the code looks clean. If you could answer this, that will help me a lot. Thanks..
  Re :How to implement paging and sorting in asp.net Gridview control?   
Posted by Siddhesh S Adarkar
on 7/6/2014 2:59:19 AM
Points : 10

Hello Friends ....

I am new to .Net Technologies. It seems that GetData() method is called each time for the paging & sorting purpose. However this method connects to database each time, fetching records from Database.
Can we store the Dataset/ DataView in View State, so that it can be used for used for further sorting or binding.???
  Re :How to implement paging and sorting in asp.net Gridview control?   
Posted by junodeveloper
on 9/12/2014 6:33:13 PM
Points : 10

really great work man awesome
  Re :How to implement paging and sorting in asp.net Gridview control?   
Posted by mudzakkir
on 10/15/2014 3:53:21 AM
Points : 10

Really nice, Sir

Submit feedback about this article

Please sign in to post feedback

Latest Posts