SIGN UP MEMBER LOGIN:    
ARTICLE

Paging and Sorting in ASP.Net GridView

Posted by Manoj Sevda Articles | ASP.NET Programming October 31, 2011
The GridView control provides you with an easy way to display the number of items on a page without taking much space, with the help of paging. You can enable the paging feature in the GridView control in seconds. The built-in paging is pretty good if you are fetching less than 100 items.
Reader Level:
Download Files:
 

The GridView is a great web control when you want to display data from the database. Out of the box it has built-in paging, sorting and a multitude of events that you can control. Recently I thought about the paging aspect of the control and thought about how you could display the page numbers as something other than numbers, such as letters. Well here's the answer! This code has not been requested by any of my customers but I thought it would be cool to try it out!

To begin with open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application.

Open the Default.aspx page and add a GridView control to the page.

Here, I am going to demonstrate a sample on GridView Custom Paging. I want to display records from Product tables.

GridView Markup

<asp:GridView CellSpacing="1" ID="gvProduct" PageSize="25" Width="100%" runat="server"
                    AutoGenerateColumns="False" GridLines="None" AllowPaging="True" AllowSorting="True"
                    OnPageIndexChanging="gvProduct_PageIndexChanging" OnRowDataBound="gvProduct_RowDataBound"
                    OnSorting="gvProduct_Sorting">
                    <RowStyle BackColor="#E3EAEB" VerticalAlign="Middle" />
                    <HeaderStyle BackColor="#1C5E55" HorizontalAlign="Left" Font-Bold="True" ForeColor="White" />
                    <AlternatingRowStyle BackColor="White" />
                    <Columns>
                        <asp:BoundField HeaderText="Sr.No.">
                            <HeaderStyle HorizontalAlign="Center" />
                            <ItemStyle HorizontalAlign="Center" Width="10%" />
                        </asp:BoundField>
                        <asp:BoundField HeaderText="ProductID" SortExpression="ProductID" DataField="ProductID" />
                        <asp:BoundField HeaderText="ProductName" SortExpression="ProductName" DataField="ProductName" />
                        <asp:BoundField HeaderText="UnitPrice" SortExpression="UnitPrice" DataField="UnitPrice" />
                    </Columns>
                    <EmptyDataTemplate>
                        Sorry! Employee record was not found.
                    </EmptyDataTemplate>
                    <EmptyDataRowStyle HorizontalAlign="Center" Font-Size="Larger" Font-Bold="true" />
                    <PagerSettings Mode="NextPrevious" Position="TopAndBottom" NextPageText="Next" PreviousPageText="Prev"
                        FirstPageText="First" LastPageText="Last" />
                    <PagerTemplate>
                        <asp:Button ID="Button1" runat="server" Text="First" CommandName="Page" CommandArgument="First"
                            Enabled="<%# gvProduct.PageIndex > 0 %>" />
                        <asp:Button ID="Button2" runat="server" Text="Prev" CommandName="Page" CommandArgument="Prev"
                            Enabled="<%# gvProduct.PageIndex > 0 %>" />
                        <span id="Span1" runat="server">Page
                            <%= gvProduct.PageIndex + 1%>
                            of
                            <%= gvProduct.PageCount%>
                        </span>
                        <asp:Button ID="Button3" runat="server" Text="Next" CommandName="Page" CommandArgument="Next"
                            Enabled="<%# gvProduct.PageIndex + 1 < gvProduct.PageCount %>" />
                        <asp:Button ID="Button4" runat="server" Text="Last" CommandName="Page" CommandArgument="Last"
                            Enabled="<%# gvProduct.PageIndex + 1 < gvProduct.PageCount %>" />
                    </PagerTemplate>
                </asp:GridView>

Binding data

Now we need to bind custom result to our gridview, I have define a private function BindData which will take currentPage number as a input and populate result accordingly and return Total record count

private void BindData()
    {
        string connectionString = WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
        string selectSQL = "SELECT ProductID, ProductName, UnitPrice FROM Products";
        SqlConnection con = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();

        adapter.Fill(ds, "Products");

        try
        {
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataView DV = ds.Tables[0].DefaultView;

                if (Session["sortBy"] != null)
                {
                    DV.Sort = Session["sortBy"].ToString();
                }
                gvProduct.DataSource = DV;
                gvProduct.DataBind();
            }
            else
            {
                gvProduct.DataSource = null;
                gvProduct.DataBind();
            }
        }
        catch (Exception oException)
        {
            // The connection failed. Display an error message.
        }
    }

Sorting Event

protected void gvProduct_Sorting(object sender, GridViewSortEventArgs e)
    {
        Session["sortBy"] = e.SortExpression;
        BindData();
    }

Paging Event

protected void gvProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvProduct.PageIndex = e.NewPageIndex;
        BindData();
    }

Page Load

On page load we need to call Bind Data functions

 protected void Page_Load(object sender, EventArgs e)
    {
        Session["sortBy"] = null;
        if (!IsPostBack)
        {
            BindData();
        }
    }

Or download attached file for GridView Custom Paging in ASP.NET 3.5.

Login to add your contents and source code to this article
share this article :
post comment
 
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications. Visit DynamicPDF here
    Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor