Click here to Skip to main content
15,888,984 members
Articles / Web Development / ASP.NET
Tip/Trick

Custom Paging Control

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
20 Apr 2013CPOL2 min read 24.3K   641   6   10
Custom paging control for repeaters

Introduction

Displaying data in grids is a usual task in a web developer's life. Sometimes, the number of records to display are more than a user can handle (or needs) in one page. Plus, loading too much data in one page will make page load slow and frustrating. That's why we need to display data one page at a time.

Pagination can be done easily in a DataGrid control. But, what if you wish to display your data in a repeater? In this tip, I will explain how to use my custom paging control to display data in a table using a repeater.

Using the Code

Step 1: Create Repeater

On your web page, create a new repeater.

ASP.NET
<asp:Repeater ID="repeater" runat="server">
           <HeaderTemplate>
               <table class="datagrid">
                   <thead>
                       <tr>
                           <th style="width: 50px;">
                               Fruit
                           </th>
                           <th style="width: 50px;">
                               Color
                           </th>
                       </tr>
                   </thead>
                   <tbody>
           </HeaderTemplate>
           <ItemTemplate>
               <tr>
                   <td>
                       <%# Eval("Fruit")%>
                   </td>
                   <td>
                       <%# Eval("Color")%>
                   </td>
               </tr>
           </ItemTemplate>
           <FooterTemplate>
               </tbody>
               </table>
           </FooterTemplate>
       </asp:Repeater>

Step 2: Add Paging Control

We can drag the PagingControl to page designer or we can add it manually under the repeater. We will need to set the PageSize attribute which is the number of records displayed per page.

ASP.NET
<uc1:PagingControl ID="PagingControl1" runat="server" PageSize="2" /> 

If the control is added manually, don't forget to register the control on the top of the page.

ASP.NET
<%@ Register Src="PagingControl.ascx" TagName="PagingControl" TagPrefix="uc1" %>  

Step 3: Populate Data

Let's create some data to display in the repeater. Create a new function, let's call it GetDataSource with the following signature:

C#
private DataTable GetDataSource(int firstItemIndex, int lastItemIndex, out int totalRecordsCount)  

This function takes as parameters the zero based index of the first item to be displayed on the current page and the zero based index of the last item. This function takes an output parameter which is the total number of records. The paging control needs the total number of records to calculate the number of pages.

For the sake of simplicity, this function creates a DataTable and adds 5 records to it. Then set the output parameter totalRecordsCount. Only records to be displayed on the current page will be returned.

C#
private DataTable GetDataSource(int firstItemIndex, int lastItemIndex, out int totalRecordsCount)
        {       
            //create datatable          
            DataTable table = new DataTable();            
            table.Columns.Add("Fruit");
            table.Columns.Add("Color");
 
            DataRow row = table.NewRow();
            row["Fruit"] = "Apple";
            row["Color"] = "Red";
            table.Rows.Add(row);
 
            row = table.NewRow();
            row["Fruit"] = "Banana";
            row["Color"] = "Yellow";
            table.Rows.Add(row);
 
            row = table.NewRow();
            row["Fruit"] = "Strawberry";
            row["Color"] = "Red";
            table.Rows.Add(row);
 
            row = table.NewRow();
            row["Fruit"] = "Orange";
            row["Color"] = "Orange";
            table.Rows.Add(row);
 
            row = table.NewRow();
            row["Fruit"] = "Watermelon"; 
            row["Color"] = "Green";
            table.Rows.Add(row); 
           
            //set total records count
            totalRecordsCount = table.Rows.Count;
 
            //return only records to be shown on the current page
            return table.AsEnumerable().Skip(firstItemIndex).Take
            (lastItemIndex - firstItemIndex + 1).CopyToDataTable();
        }   
Note

In real life, data will be returned from a database. It is totally useless to select all records from the database then only return the 10 or 20 records that will be displayed on the current page. So, what's the use of SQL to return the total records count and another statement to return data to be displayed. To return paged results using SQL Server, please refer to this article.

Step 4: Bind Data

This function simply binds data to the repeater. What is important in this function is setting the TotalRecordsCount of the PagingControl so the control can calculate the number of pages. And calling PagingControl1.BuildPages(). Calling this function creates the page numbers links of the paging control.

C#
private void BindRepeater()
        {
            int totalCount = 0;
 
            //get records to be shown in the current page
            DataTable table = GetDataSource
            (PagingControl1.FirstItemIndex, PagingControl1.MaxItemIndex, out totalCount);
 
            //bind repeater 
            repeater.DataSource = table;
            repeater.DataBind();
            
            //Set number of records
            PagingControl1.TotalRecordsCount = totalCount;
 
            //build control
            PagingControl1.BuildPages();
        }  

Let's call this on page load:

C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindRepeater();                
            }
        } 

Step 5: Handle Paging Control Events

When a user clicks a link on the paging control, the click event is bubbled to the parent page. We should handle that. Here, we only call BindRepeater() to display data of the selected page.

C#
protected override bool OnBubbleEvent(object source, EventArgs args)
        {
            CommandEventArgs e = (CommandEventArgs)args;
 
            if (e != null)
            {
                //Go to Next Page
                if (string.Equals(e.CommandName, "MoveNext", StringComparison.OrdinalIgnoreCase))
                {
                    BindRepeater();
                }
                //Go to Previous Page
                else if (string.Equals(e.CommandName, "MovePrev", StringComparison.OrdinalIgnoreCase))
                {
                    BindRepeater();
                }
                //Go to First Page
                else if (string.Equals(e.CommandName, "MoveFirst", StringComparison.OrdinalIgnoreCase))
                {
                    BindRepeater();
                }
                //Go to Last Page
                else if (string.Equals(e.CommandName, "MoveLast", StringComparison.OrdinalIgnoreCase))
                {
                    BindRepeater();
                }
                //Go to Page Number ...
                else if (string.Equals(e.CommandName, "GoToPage", StringComparison.OrdinalIgnoreCase))
                {
                    BindRepeater();
                }
            }
 
            return base.OnBubbleEvent(source, e);
        }

Step 6: (Optional)

Feel free to play with CSS to change the look and feel of the control. This implementation is very basic.

History

  • 20th April, 2013: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer Freelance
Egypt Egypt
Freelance Web Developer

Comments and Discussions

 
QuestionHow to handle OnBubbleEvent event for multiple grids in the same page. Pin
Praveen Kumar Gundu13-Oct-14 8:13
Praveen Kumar Gundu13-Oct-14 8:13 
AnswerRe: How to handle OnBubbleEvent event for multiple grids in the same page. Pin
Aliaa Ezzat17-Oct-14 1:34
Aliaa Ezzat17-Oct-14 1:34 
GeneralRe: How to handle OnBubbleEvent event for multiple grids in the same page. Pin
Praveen Kumar Gundu31-Oct-14 19:10
Praveen Kumar Gundu31-Oct-14 19:10 
GeneralRe: How to handle OnBubbleEvent event for multiple grids in the same page. Pin
Aliaa Ezzat1-Nov-14 1:56
Aliaa Ezzat1-Nov-14 1:56 
QuestionOnBubbleEvent Pin
accdeveloper31-Mar-14 14:44
accdeveloper31-Mar-14 14:44 
AnswerRe: OnBubbleEvent Pin
Aliaa Ezzat1-Apr-14 1:39
Aliaa Ezzat1-Apr-14 1:39 
GeneralRe: OnBubbleEvent Pin
accdeveloper1-Apr-14 7:48
accdeveloper1-Apr-14 7:48 
GeneralRe: OnBubbleEvent Pin
Aliaa Ezzat1-Apr-14 9:36
Aliaa Ezzat1-Apr-14 9:36 
QuestionImplement with database Pin
yongga10-Jan-14 21:47
yongga10-Jan-14 21:47 
AnswerRe: Implement with database Pin
Aliaa Ezzat12-Jan-14 23:42
Aliaa Ezzat12-Jan-14 23:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.