Share via


ASP.NET DataGrid Custom Paging

Introduction

In this blog, I will demonstrate a technique where you can customize your paging behavior in combination with the standard DataGrid control’s NumericPage paging feature. The standard paging modes for the DataGrid are NumericPages and PrevNext. You can enable AllowCustomPaging to do a more complex paging customization, but that requires you to manipulate the VirtualItemCount and others which isn’t always necessary for many paging customization needs. The technique I describe here is the simplest way that I know how to accomplish custom paging for the ASP.NET DataGrid control.

Technique

The DataGrid creates two paging rows one at the top of the table if the option is to display the paging navigation there and/or another one at the bottom of the table if the option is to display there. If you don’t use the auto-generated columns, the paging table cell spans across the entire table and there is a Controls list that has the numeric page links. This technique for adding custom paging behaviors to the DataGrid control requires manipulating this Controls list. Here are the main steps that you need to do.

1. Add the Init event handler for the DataGrid control – in this Init event handler, create the additional navigation controls, such as, ImageButton or LinkButton, to be added to the paging Controls list. If you would like to have the paging behavior to include First Page, Previous Page, Numeric Pages, Next Page, and Last Page, you will need to add First Page, Previous Page, Next Page, and Last Page link controls to the Controls list.

2. For each additional navigation link, create an event handler for the Click event. This allows your program to handle the event when the user clicks on the link.

3. Add the ItemCreated event handler for the DataGrid control – you will add the additional navigation links to the Controls list in this event handler.

Screenshots

Using the AdventureWorksLT2008, here is the list from the Customer table.

Source Code

Here is the entire source code for the default.aspx.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DataGridCustomPaging._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" >

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

   

        <asp:SqlDataSource ID="SqlDataSource1" runat="server"

            ConnectionString="<%$ ConnectionStrings:AdventureWorksLT2008ConnectionString %>" SelectCommand="SELECT [CustomerID], [CompanyName], [FirstName], [MiddleName], [LastName], [EmailAddress], [Phone] FROM [SalesLT].[Customer]

"></asp:SqlDataSource>

        <asp:DataGrid ID="dgCustomer" runat="server" AllowPaging="True"

            AllowSorting="True" AutoGenerateColumns="False" BackColor="White"

            BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4"

            DataSourceID="SqlDataSource1" oninit="dgCustomer_Init"

            onitemcreated="dgCustomer_ItemCreated"

            onpageindexchanged="dgCustomer_PageIndexChanged" >

            <FooterStyle BackColor="#99CCCC" ForeColor="#003399" Wrap="False" />

            <SelectedItemStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />

            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left"

                Mode="NumericPages" VerticalAlign="Top" Wrap="False" />

            <ItemStyle BackColor="White" ForeColor="#003399" />

            <Columns>

                <asp:BoundColumn DataField="CustomerID" HeaderText="Customer ID">

                </asp:BoundColumn>

                <asp:BoundColumn DataField="companyname" HeaderText="Company Name">

                </asp:BoundColumn>

                <asp:BoundColumn DataField="FirstName" HeaderText="First Name">

                </asp:BoundColumn>

                <asp:BoundColumn DataField="MiddleName" HeaderText="Middle Name">

                </asp:BoundColumn>

                <asp:BoundColumn DataField="LastName" HeaderText="Last Name"></asp:BoundColumn>

            </Columns>

            <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF"

                Wrap="False" />

        </asp:DataGrid>

   

    </div>

    </form>

</body>

</html>

 

Here is the entire source code for default.aspx.cs.

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace DataGridCustomPaging

{

    public partial class _Default : System.Web.UI.Page

    {

        LinkButton lbFirstPage = null;

        LinkButton lbPreviousPage = null;

        LinkButton lbNextPage = null;

        LinkButton lbLastPage = null;

        protected void Page_Load(object sender, EventArgs e)

        {

        }

        protected void dgCustomer_Init(object sender, EventArgs e)

        {

            lbFirstPage = new LinkButton();

            lbFirstPage.ID = "lbFirstPage";

            lbFirstPage.Text = "First";

            lbFirstPage.Click += new EventHandler(lbFirstPage_Click);

            lbPreviousPage = new LinkButton();

            lbPreviousPage.ID = "lbPreviousPage";

            lbPreviousPage.Text = "Previous";

            lbPreviousPage.Click += new EventHandler(lbPreviousPage_Click);

            lbNextPage = new LinkButton();

            lbNextPage.ID = "lbNextPage";

            lbNextPage.Text = "Next";

            lbNextPage.Click += new EventHandler(lbNextPage_Click);

           

            lbLastPage = new LinkButton();

            lbLastPage.ID = "lbLastPage";

            lbLastPage.Text = "Last";

            lbLastPage.Click += new EventHandler(lbLastPage_Click);

        }

        void lbLastPage_Click(object sender, EventArgs e)

        {

            dgCustomer.CurrentPageIndex = dgCustomer.PageCount - 1;

            dgCustomer.DataBind();

        }

        void lbNextPage_Click(object sender, EventArgs e)

        {

            if (dgCustomer.CurrentPageIndex < (dgCustomer.PageCount - 1))

            {

                dgCustomer.CurrentPageIndex++;

                dgCustomer.DataBind();

            }

        }

        void lbPreviousPage_Click(object sender, EventArgs e)

        {

            if (dgCustomer.CurrentPageIndex > 0)

            {

                dgCustomer.CurrentPageIndex--;

                dgCustomer.DataBind();

            }

        }

        void lbFirstPage_Click(object sender, EventArgs e)

        {

            dgCustomer.CurrentPageIndex = 0;

            dgCustomer.DataBind();

        }

        protected void dgCustomer_PageIndexChanged(object source, DataGridPageChangedEventArgs e)

        {

            dgCustomer.CurrentPageIndex = e.NewPageIndex;

            dgCustomer.DataBind();

        }

        protected void dgCustomer_ItemCreated(object sender, DataGridItemEventArgs e)

        {

            if (e.Item.ItemType == ListItemType.Pager)

  {

                // add the previous page link

                if (dgCustomer.CurrentPageIndex > 0)

                {

                    if (e.Item.Cells[0].FindControl("lbPreviousPage") == null)

                    {

                        e.Item.Cells[0].Controls.AddAt(0, new LiteralControl("&nbsp;"));

                        e.Item.Cells[0].Controls.AddAt(0, lbPreviousPage);

                    }

                }

                // add the first page link

                if (dgCustomer.PageCount > 0)

                {

                    if (e.Item.Cells[0].FindControl("lbFirstPage") == null)

                    {

                        e.Item.Cells[0].Controls.AddAt(0, new LiteralControl("&nbsp;"));

     e.Item.Cells[0].Controls.AddAt(0, lbFirstPage);

                    }

                }

                // add the next page link

                if (dgCustomer.CurrentPageIndex < (dgCustomer.PageCount - 1))

                {

                    if (e.Item.Cells[0].FindControl("lbNextPage") == null)

                    {

                        e.Item.Cells[0].Controls.Add(new LiteralControl("&nbsp;"));

                        e.Item.Cells[0].Controls.Add(lbNextPage);

         }

                }

                // add the first page link

                if (dgCustomer.PageCount > 0)

                {

                    if (e.Item.Cells[0].FindControl("lbLastPage") == null)

                    {

                        e.Item.Cells[0].Controls.Add(new LiteralControl("&nbsp;"));

                        e.Item.Cells[0].Controls.Add(lbLastPage);

                    }

                }

            }

        }

    }

}

 

Conclusion

This technique shows you how to customize your navigation behaviors with very simple steps and still leveraging the built-in paging feature of the DataGrid control.  I hope that this is useful for your application.