Click here to Skip to main content
15,031,219 members
Articles / Web Development / ASP.NET
Posted 10 Oct 2015


15 bookmarked

Perfect Pagination with Repeater Control in ASP.NET C#

Rate me:
Please Sign up or sign in to vote.
4.96/5 (15 votes)
10 Oct 2015CPOL3 min read
Perfect Pagination with Repeater Control in ASP.NET C#


Unlike the GridView control in ASP.NET, the Repeater control doesn't supported the pagination function when displaying a long data on your web page. So, if you guys wanted to display a huge data on a page, what should you do? Instead of using Repeater control, you will use the GridView control? I think a lot of people will have the same thought.

However, if we only display the data on web page as in the table style, then I think we can use the GridView as a good choice. But, if you want to display the data on your web page with the free style, then you cannot. Meaning, we have to use the Repeater control as a replacement for GridView.

Should Know Before Starting

In this guideline, I'm going to use the Visual Studio Enterprise 2015, .NET Framework 4.5.2, ADO.NET, ASP.NET C# programming language, Repeater and UpdatePanel controls to show you "How to implement the pagination function with Repeater control". I think you guys we be thinking that we have a lot of guidelines on the internet for implementing this one. But, I believed most of them just showed you guys a basic of concept with the limitation of functions and it doesn't meet your expectation.

If you guys are reading this guideline, then I think you do not need to research other solutions on the internet anymore, because I think it covered all the functions you wanted to implement for your web page. Also, using UpdatePanel in this demo will help to go to other pages without refreshing the web page.

So, let's get started and don't forget to give me a vote after reading it. Also, the output for this demo will look like this screenshot:

Image 1

Steps For Implemeting the Code

Step 1

Firstly, I go ahead to create a table namely tblPerson in SQL database with the following fields:

CREATE TABLE [dbo].[tblPerson](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    [createdDate] [datetime] NULL,
    [id] ASC

Note: I will also include the script to create tables and insert testing data in the Database folder in the attached source code, so you guys can see details when downloading the source code to your local.

Step 2

Insert some testing data into tblPerson table. You guys can use the script mentioned in the above step to create.

Step 3

Open Visual Studio, then create a new web project or new web page.

Step 4

Open Web.config to add connectionStrings tag. You should enter the SQL database server information inside this tag to make your website able to work with the database.

    <add name="stringConnection" connectionString="Data Source = CHIENVH-PC;
	Initial Catalog=MyDB;Persist Security Info=True;User ID=sa; Password=123456789;"/>

Step 5

Create a web page with any name, in this guideline I will name it as Default.aspx. Copy below front end code into that page:

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

<!DOCTYPE html>

<html xmlns="">
<head runat="server">
    <title>Perfect Pagination With Repeater and ASP.Net C#</title>
    <style type="text/css">
        .auto-style1 {
            width: 100%;

        .auto-style3 {
            width: 162px;

        table {
            border-collapse: collapse;

        table, td, th {
            border: 1px solid blue;

        th {
            background-color: dodgerblue;
            color: white;
    <form id="form1" runat="server">
        <asp:ScriptManager ID="MainScriptManager" runat="server" />
        <asp:UpdatePanel ID="pnlHelloWorld" runat="server">
                    <asp:Repeater ID="rptResult" runat="server">
                            <table class="auto-style1">
                                    <th>Created Date</th>
                                <td><%#Eval("Id") %></td>
                                <td><%#Eval("Name") %></td>
                                <td><%#Eval("Address") %></td>
                                <td><%#Eval("createdDate") %></td>

                <div style="margin-top: 20px;">
                    <table style="width: 600px;">
                                <asp:LinkButton ID="lbFirst" runat="server" 
                                <asp:LinkButton ID="lbPrevious" runat="server" 
                                <asp:DataList ID="rptPaging" runat="server"
                                        <asp:LinkButton ID="lbPaging" runat="server"
                                            CommandArgument='<%# Eval("PageIndex") %>' 
                                            Text='<%# Eval("PageText") %> ' Width="20px">
                                <asp:LinkButton ID="lbNext" runat="server" 
                                <asp:LinkButton ID="lbLast" runat="server" 
                                <asp:Label ID="lblpage" runat="server" Text=""></asp:Label>


Step 6

Go to code behind and copy the below code to your web page:

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PerfectPaginationWithRepeater
    public partial class Default : System.Web.UI.Page
        readonly PagedDataSource _pgsource = new PagedDataSource();
        int _firstIndex, _lastIndex;
        private int _pageSize = 10;
        private int CurrentPage
                if (ViewState["CurrentPage"] == null)
                    return 0;
                return ((int)ViewState["CurrentPage"]);
                ViewState["CurrentPage"] = value;

        protected void Page_Load(object sender, EventArgs e)
            if (Page.IsPostBack) return;

        // Get data from database/repository
        static DataTable GetDataFromDb()
            var con = new SqlConnection(ConfigurationManager.ConnectionStrings
            var da = new SqlDataAdapter("Select Id, Name, Address, 
		CreatedDate From tblPerson Order By Id desc", con);
            var dt = new DataTable();
            return dt;

        // Bind PagedDataSource into Repeater
        private void BindDataIntoRepeater()
            var dt = GetDataFromDb();
            _pgsource.DataSource = dt.DefaultView;
            _pgsource.AllowPaging = true;
            // Number of items to be displayed in the Repeater
            _pgsource.PageSize = _pageSize;
            _pgsource.CurrentPageIndex = CurrentPage;
            // Keep the Total pages in View State
            ViewState["TotalPages"] = _pgsource.PageCount;
            // Example: "Page 1 of 10"
            lblpage.Text = "Page " + (CurrentPage + 1) + " of " + _pgsource.PageCount;
            // Enable First, Last, Previous, Next buttons
            lbPrevious.Enabled = !_pgsource.IsFirstPage;
            lbNext.Enabled = !_pgsource.IsLastPage;
            lbFirst.Enabled = !_pgsource.IsFirstPage;
            lbLast.Enabled = !_pgsource.IsLastPage;

            // Bind data into repeater
            rptResult.DataSource = _pgsource;

            // Call the function to do paging

        private void HandlePaging()
            var dt = new DataTable();
            dt.Columns.Add("PageIndex"); //Start from 0
            dt.Columns.Add("PageText"); //Start from 1

            _firstIndex = CurrentPage - 5;
            if (CurrentPage > 5)
                _lastIndex = CurrentPage + 5;
                _lastIndex = 10;

            // Check last page is greater than total page then reduced it 
            // to total no. of page is last index
            if (_lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
                _lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
                _firstIndex = _lastIndex - 10;

            if (_firstIndex < 0)
                _firstIndex = 0;

            // Now creating page number based on above first and last page index
            for (var i = _firstIndex; i < _lastIndex; i++)
                var dr = dt.NewRow();
                dr[0] = i;
                dr[1] = i + 1;

            rptPaging.DataSource = dt;

        protected void lbFirst_Click(object sender, EventArgs e)
            CurrentPage = 0;
        protected void lbLast_Click(object sender, EventArgs e)
            CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
        protected void lbPrevious_Click(object sender, EventArgs e)
            CurrentPage -= 1;
        protected void lbNext_Click(object sender, EventArgs e)
            CurrentPage += 1;

        protected void rptPaging_ItemCommand(object source, DataListCommandEventArgs e)
            if (!e.CommandName.Equals("newPage")) return;
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());

        protected void rptPaging_ItemDataBound(object sender, DataListItemEventArgs e)
            var lnkPage = (LinkButton)e.Item.FindControl("lbPaging");
            if (lnkPage.CommandArgument != CurrentPage.ToString()) return;
            lnkPage.Enabled = false;
            lnkPage.BackColor = Color.FromName("#00FF00");

Step 7

Finally, just run your web page to enjoy the functions. Let me know if you guys have any questions. I will try to answer ASAP.


  • Sunday, October 11, 2015: Initial version


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


About the Author

Product Manager
Vietnam Vietnam
Updated LinkedIn:

I am currently working as the position of project manager for a long time. Had to take care a lot of projects at the same times, so I don't have many free times in a day for contributing the articles, tips/tricks on codeproject.
While I was at the previous company sometimes I participated in training courses for new employees, so I have good teaching skills and ability to convey information to others. Meaning in each my post I will try to explain more detail as possible for the junior devs are able to implement/understand what's I have done.

Also, would like to share my responsibilities for current position:

• Coordinate internal resources and third parties/vendors for the flawless execution of projects
• Ensure that all projects are delivered on-time, within scope and within budget
• Assist in the definition of project scope and objectives, involving all relevant stakeholders and ensuring technical feasibility
• Ensure resource availability and allocation
• Develop a detailed project plan to monitor and track progress
• Report and escalate to management as needed
• Perform risk management to minimize project risks
• Establish and maintain relationships with third parties/vendors
• Create and maintain comprehensive project documentation
• Support team members to solve technical issues

Opening and looking forward to finding suitable jobs.

Comments and Discussions

QuestionPerfect Article. My savior. Thank you. Pin
Member 1422778612-Apr-19 0:31
MemberMember 1422778612-Apr-19 0:31 
QuestionGreat, Wonderfull Pin
Mustafa_Alhelo31-May-18 4:51
MemberMustafa_Alhelo31-May-18 4:51 
GeneralMy vote of 5 Pin
Mustafa_Alhelo31-May-18 4:50
MemberMustafa_Alhelo31-May-18 4:50 
QuestionThanks a Lot ChienVH!! valuable contribution to .net community Pin
DevCodeNext20-Feb-18 1:30
MemberDevCodeNext20-Feb-18 1:30 
PraisePraise Pin
Member 1362510815-Jan-18 21:41
MemberMember 1362510815-Jan-18 21:41 
PraiseBeginner Developer Pin
Member 1353264021-Dec-17 1:34
MemberMember 1353264021-Dec-17 1:34 
PraiseNice! Pin
ArjanRuter28-Sep-17 23:27
MemberArjanRuter28-Sep-17 23:27 
PraiseThis is the real bomb. followed your codes and i got exactly what i wanted. Thanks ma Pin
Mcbaloo31-Jan-17 3:50
MemberMcbaloo31-Jan-17 3:50 
GeneralRe: This is the real bomb. followed your codes and i got exactly what i wanted. Thanks ma Pin
ChienVH2-Feb-17 2:10
MemberChienVH2-Feb-17 2:10 
QuestionLimit display of Page Numbers Pin
Andy Baba31-Aug-16 20:34
MemberAndy Baba31-Aug-16 20:34 
GeneralGreat job Pin
Ahmed Abdullai8-Jun-16 22:11
professionalAhmed Abdullai8-Jun-16 22:11 
GeneralRe: Great job Pin
ChienVH10-Jun-16 1:30
MemberChienVH10-Jun-16 1:30 
Questionhuge database Pin
Member 73027310-May-16 0:31
MemberMember 73027310-May-16 0:31 
GeneralMy vote of 5 Pin
Farhad Reza15-Oct-15 21:00
MemberFarhad Reza15-Oct-15 21:00 
QuestionI wouldn't call it perfect Pin
HaBiX12-Oct-15 5:12
MemberHaBiX12-Oct-15 5:12 
Your aim was to handle displaying of big data, but this approach will fail in real world.

Consider having million records, that you want to page by 20 records.. you load everything into memory, then copy 20 records to new datatable, to show that page.
Now consider 100 users doing the same thing at once..

The right way of doing it is writing sql query that will only return 20 records from selected page.
AnswerRe: I wouldn't call it perfect Pin
ChienVH13-Oct-15 7:33
MemberChienVH13-Oct-15 7:33 
QuestionNice article Pin
Santhakumar M11-Oct-15 7:03
professionalSanthakumar M11-Oct-15 7:03 
AnswerRe: Nice article Pin
ChienVH13-Oct-15 7:37
MemberChienVH13-Oct-15 7:37 

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.