How to apply custom paging to a DataGrid control

Tripati_tutu
Posted by in ASP.NET category on for Beginner level | Points: 150 | Views : 10490 red flag

In this article I have explained how you can apply custom paging to a DataGrid control. With the help of this custom paging you can easily navigate the records one by one present in the DataGrid control. Also I have given a code snippet that will give you the brief idea that how you can apply custom paging to the controls.

Introduction

ASP.NET DataGrid control displays data in a tabular format and also supports features for selecting, sorting, paging, and editing the data. The ASP.NET DataGrid control reduces a lot of task that we had been doing in the ASP applications like retrieve a recordset, loop through the results one by one, struggle to format the data in HTML table manipulating the rows and column dynamically etc.

Here I have given a demonstrate 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 control 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.

Below I have given 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 when you want to apply custom paging to the controls.

·   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.

·   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.

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

Sample Output:

Here is the list of employee in Emp table present in the database. By using First, Previous, Next, and Last you can navigate to the records in forward and backward direction.


                    

Source Code:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_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>Data Grid with Paging</title>

</head>

<body>

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

    <div>

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

            ConnectionString='<%$ ConnectionStrings:ConnStr %>' SelectCommand="select [Eid],           [Ename], [Sal], [Deptno] from Emp">

        </asp:SqlDataSource>

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

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

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

            DataSourceID="SqlDataSource1" oninit="dgEmp_Init"

            onitemcreated="dgEmp_ItemCreated"

            onpageindexchanged="dgEmp_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="Eid" HeaderText="Employee ID">

                </asp:BoundColumn>

                <asp:BoundColumn DataField="Ename" HeaderText="Employee Name">

                </asp:BoundColumn>

                <asp:BoundColumn DataField="Sal" HeaderText="Salary">

                </asp:BoundColumn>

                <asp:BoundColumn DataField="Deptno" HeaderText="Department No">

                </asp:BoundColumn>

            </Columns>

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

                     Wrap="False" />

        </asp:DataGrid>

    </div>

    </form>

</body>

</html>

 

Here I have authenticated the SQL Server as windows authentication. So in web.config file you have to mention the below mentioned connection string to connect to the database.

 

<connectionStrings>

     <add name ="ConnStr"connectionString="Server=server name;Database=database name; Trusted_Connection=Yes;"/>

</connectionStrings>

 

Here I have used Sql DataSource to display the employee table data from the database. I have taken a DataGrid control where I have applied custom paging to show the Employee detail. In this DataGrid control I have mentioned different event methods to use it in my application. These are explained as below.

 a)    OnInit: This is a built-in method of the control class that is called when the Init event if fired. The OnInit client-side event handler is called when the structure is first constructed. This method always call to raise Init event. The purpose of this is to set various properties of the controls at runtime.

b)    OnItemCreated: The OnItemCreated event is raised when an item in the DataGrid control is created. At this time of event call the data is bound to the control. The ItemCreated event is commonly used to control the content and appearance of a row in the DataGrid control. This event fires when a control is bound as well as when the control is recreated from the viewstate. This is usually used when you are templating controls and need to set them up. Normally we can say, a DataGrid displays data from a DataSet. The DataGrid has the OnItemCreated event.

c)     OnPageIndexChanged: The OnPageIndexChanged method is used to provide a custom handler for the PageIndexChanged event. The PageIndexChanged event is raised when one of the page selection elements is clicked or when one of the pager buttons is clicked, but after the DataGrid control handles the paging operation. It enables you to provide an event-handling method that performs a custom routine, such as a custom paging operation, whenever this event occurs. When DataGrid with paging enabled shows numeric links for pages, you will get OnPageIndexChanged event fired when user clicks on any of the page links.

 

Below is Code-Behind code of .aspx Web Page:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

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 dgEmp_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)

    {

        dgEmp.CurrentPageIndex = dgEmp.PageCount - 1;

        dgEmp.DataBind();

    }

    void lbNextPage_Click(object sender, EventArgs e)

    {

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

        {

            dgEmp.CurrentPageIndex++;

            dgEmp.DataBind();

        }

    }

    void lbPreviousPage_Click(object sender, EventArgs e)

    {

        if (dgEmp.CurrentPageIndex > 0)

        {

            dgEmp.CurrentPageIndex--;

            dgEmp.DataBind();

        }

    }

    void lbFirstPage_Click(object sender, EventArgs e)

    {

        dgEmp.CurrentPageIndex = 0;

        dgEmp.DataBind();

    }

 

    protected void dgEmp_PageIndexChanged(object source, DataGridPageChangedEventArgs e)

    {

        dgEmp.CurrentPageIndex = e.NewPageIndex;

        dgEmp.DataBind();

    }

 

    protected void dgEmp_ItemCreated(object sender, DataGridItemEventArgs e)

    {

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

        {

            // add the previous page link

            if (dgEmp.CurrentPageIndex > 0)

            {

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

                {

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

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

                }

            }

            // add the first page link

            if (dgEmp.PageCount > 0)

            {

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

                {

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

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

                }

            }

            // add the next page link

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

            {

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

                {

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

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

                }

            }

            // add the first page link

            if (dgEmp.PageCount > 0)

            {

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

                {

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

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

                }

            }

        }

    }

}



Conclusion

The above example shows how you can apply custom paging to a DataGrid control. With the help of this custom paging you can easily navigate the records one by one present in the DataGrid control. The above code snippet will give the brief idea that how you can apply custom paging to the controls.

Page copy protected against web site content infringement by Copyscape

About the Author

Tripati_tutu
Full Name: K.Tripati Balaji Subudhi
Member Level: Bronze
Member Status: Member
Member Since: 9/20/2010 5:58:39 AM
Country: India

http://www.dotnetfunda.com/profile/Tripati_tutu.aspx

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)