-->

How to implement Custom Paging and Sorting in ASP.Net Gridview



Introduction

In this post I am explain how to implement Custom Paging and Sorting in ASP.Net GridView.

In one of my previous article I have explained How to implement Custom Paging in ASP.Net GridView using SQL Server Stored Procedure . In this article I would like to explain how to implement custom paging and sorting in ASP.Net GridView.

Displaying data in ASP.NET Webform is very simple task using GridView with some great (default) functionality like sorting and paging. We can use Gridview's default paging by setting it's property AllowPaging="true" and sotring by setting AllowSorting="True". The GridView will show the pager itself depending on the PageSize and total records. But this way is very tedious and degrades the performance of the application because everytime the PageIndex changes, the GridView will be bound with the complete datasource that is not required at all, as we need to show only data to the corresponding PageIndex. To improve the performance of the web application I am going to explain how to implement custom paging and oorting in ASP.Net GridView.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net web forms application > Entry Application Name > Click OK.

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for stote data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below


Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Add Reference of System.Linq.Dynamic

Right Click on References > Manage NuGet Packages > Seach online with "System.Linq.Dynamic" keyword > Select & install System.Linq.Dynamic

Step-6: Add a Webpage and Design for Show Data in Gridview With Custom Paging and Sorting option.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select web form/ web form using master page under Web > Enter page name > Add.

Step-7: Write method for fetch query string value.

Please write following code...
private string QueryStringValue(string name)
{
    return Request.QueryString[name] != null ? Request.QueryString[name].ToString() : "";
}
        

Step-8: Write method for Generate gridview sort link.

Please write following code...
protected string GetSortLink(string dataField)
{
    string link = "";
    string sortname = QueryStringValue("sortname");
    string sortdir = QueryStringValue("sortdir");
    link += "sortname=" + dataField;
            
    if (sortname.Equals(dataField, StringComparison.CurrentCultureIgnoreCase))
    {
        if (sortdir.Equals("asc", StringComparison.CurrentCultureIgnoreCase))
        {
            link += "&sortdir=desc";
        }
        else
        {
            link += "&sortdir=asc";
        }
    }
    else
    {
        link += "&sortdir=asc";
    }
    return link;
}
        

Step-9: Write method for Generate Paging Link

Please write following code...
protected string GetPageLink(int noOfPage)
{
    string link = "";
    StringBuilder sb = new StringBuilder();
    bool hasPage = Request.QueryString["page"] != null ? true : false;
    string currentPage = hasPage ? QueryStringValue("page") : "1";
    for (int i = 1; i < noOfPage +1; i++)
    {
        if (currentPage == i.ToString())
        {
            sb.AppendLine(string.Format("<span>{0}</span>",i));

        }
        else if (hasPage)
        {
            sb.AppendLine(string.Format("<a href={0}>{1}</a>", Request.RawUrl.ToLower().Replace("page=" + currentPage, "page=" + i), i));
        }
        else
        {
            sb.AppendLine(string.Format("<a href='{0}{1}{2}'>{3}</a>", Request.RawUrl,
                Request.RawUrl.ToString().Contains('?') ? "&" : "?", ("page=" + i), i));
        }
    }
    link = sb.ToString();
    return link;
}
        

Step-10: Design the added webpage for show data in Gridview with Paging and sorting functionality.

HTML Code
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="MyGrid.aspx.cs" Inherits="ASPGridPagingSorting.MyGrid" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">

    <%-- I would like to add some css for looks good --%>
    <style>
        .myGrid th a.asc:after {
            content: ' ⇣';
        }
        .myGrid th a.desc:after {
            content: ' ⇡';
        }

        .myGrid {                 
                background-color: #fff; 
                margin: 5px 0 10px 0; 
                border: solid 1px #c1c1c1; 
                border-collapse:collapse; 
            }
            .myGrid td { 
                padding: 2px; 
                border: solid 1px #c1c1c1; 
                color: #717171; 
                padding:5px;
            }
            .myGrid th a {
                font-size:12pt;
                padding:5px;
            }
            .pager a,.pager span{
            padding: 5px 10px;
            border: 1px solid #3F3F3F;
            background-color: #938F8F;
            display: inline-block;
            text-decoration: none;
            color: #fff;
            }
            .pager span {
            color: black !important;
            background-color: #f4f4f4 !important;
            }
            .myGrid th{
                color: #fff; 
                background-color: #E2E2E2; 
                border-left: solid 1px #c1c1c1; 
                font-size: 0.9em; 
            }
            .myGrid .alt {
                background-color: #EFEFEF;
            }
    </style>

    <div>
        <%-- Grid  --%>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="myGrid"
            AllowPaging="true" AllowSorting="true" Width="900px">

            <Columns>
                <asp:TemplateField>
                    <ItemTemplate><%#Eval("SLID") %></ItemTemplate>
                    <HeaderTemplate>
                        <asp:HyperLink runat="server" CssClass='<%#hfSortName.Value.ToLower() == "slid"? hfSortDir.Value.ToLower() : "" %>'
                            Text="SL ID" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("SLID")) %>'>SL ID</asp:HyperLink>
                    </HeaderTemplate>
                </asp:TemplateField>

                <asp:TemplateField>
                    <ItemTemplate><%#Eval("Rank") %></ItemTemplate>
                    <HeaderTemplate>
                        <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "rank"? hfSortDir.Value.ToLower() : "" %>'
                            Text="Rank" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("rank")) %>'>Rank</asp:HyperLink>
                    </HeaderTemplate>
                </asp:TemplateField>

                <asp:TemplateField>
                    <ItemTemplate><%#Eval("CompanyName") %></ItemTemplate>
                    <HeaderTemplate>
                        <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "companyname"? hfSortDir.Value.ToLower() : "" %>'
                            Text="Company Name" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("CompanyName")) %>'>Company Name</asp:HyperLink>
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate><%#Eval("Revenue") %></ItemTemplate>
                    <HeaderTemplate>
                        <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "revenue"? hfSortDir.Value.ToLower() : "" %>'
                            Text="Revenue" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("Revenue")) %>'>Revenue</asp:HyperLink>
                    </HeaderTemplate>
                </asp:TemplateField>
                <asp:TemplateField>
                    <ItemTemplate><%#Eval("Industry") %></ItemTemplate>
                    <HeaderTemplate>
                        <asp:HyperLink ID="HyperLink1" runat="server" CssClass='<%#hfSortName.Value.ToLower() == "industry"? hfSortDir.Value.ToLower() : "" %>'
                            Text="Industry" NavigateUrl='<%#string.Format("/MyGrid.aspx?{0}",GetSortLink("Industry")) %>'>Industry</asp:HyperLink>
                    </HeaderTemplate>
                </asp:TemplateField>
            </Columns>

        </asp:GridView>
    </div>
    <div class="pager">
        <%-- Paging --%>
        <asp:Literal ID="l1Pagger" runat="server"></asp:Literal>
    </div>
    <div>
        <%-- Hidden fileds --%>
        <asp:HiddenField ID="hfCurrentPage" runat="server" Value="0" />
        <asp:HiddenField ID="hfSortName" runat="server" Value="" />
        <asp:HiddenField ID="hfSortDir" runat="server" Value="" />
    </div>
</asp:Content>

        

Step-11: Write method (in the code behind) for Populate data from database and bind to gridview.

Please write following code...
private void populate(int rowPerPage)
{
    int pageNo = 0;
    int totalPage = 0;
    //Fetch data from URL
    string sortName = string.IsNullOrEmpty(QueryStringValue("sortname")) ? "slid" : QueryStringValue("sortname");
    string sortDir = string.IsNullOrEmpty(QueryStringValue("sortdir")) ? "asc" : QueryStringValue("sortdir");
    int.TryParse(QueryStringValue("page"), out pageNo);

    //set current values
    pageNo = pageNo == 0 ? 1 : pageNo;
    hfCurrentPage.Value = pageNo.ToString();
    hfSortName.Value = sortName;
    hfSortDir.Value = sortDir;
    //Fetch data from Server 
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        int totalRecord = dc.TopCompanies.Count();
        totalPage = (totalRecord / rowPerPage) + ((totalRecord % rowPerPage) > 0 ? 1 : 0);
        var v = dc.TopCompanies.OrderBy(sortName + " " + sortDir).Skip((pageNo - 1) * rowPerPage).Take(rowPerPage).ToList();
        GridView1.DataSource = v;
        GridView1.DataBind();
    }
    //Generate Pager link
    l1Pagger.Text = GetPageLink(totalPage);
}
        

Step-12: Write following code in the page load event for load data in gridview.

Please write following code...
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        int pageSize = 10;
        GridView1.PageSize = pageSize;
        populate(pageSize);
    }
}
        

Step-13: Run Application.



Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.