How to apply pagination in repeater control using Asp.Net

 

Introduction

This article describes how to use Asp.Net data repeater control for paging with database level paging.

Asp.Net repeater control basically used for showing data which needs to be shown in repeated format. It is light weight and faster control compare to GridView. Binding a DataRepeater control is easy however binding it with pagination is harder as it does not provide any built in events for paging and sorting like GridView. It iterates over the data source and produces output without applying additional formatting.

The Gridview control has a very useful paging feature, but it's a complex control and you might not want to use it. And, if you want to use a Repeater or a DataList, they do not support paging, so what will you do ?

I recently had to use the Repeater control with large amounts of data, and the only way to do this properly is to page through the data. Out of the box the Repeater control does not have paging. This is a scenario where you can use the PagedDataSource class. This class encapsulates the paging related properties of a data-bound control. This article will not only show you how to create custom paging, but how to create it with performance in mind.

History

In the Previous articles i explained how to change or set width of ckeditor textbox area using asp.netintegrate custom image uploader control with ckeditor using asp.nethow to add asp.net membership tables to the existing databasehow to get connection string from web .config filehow to create dynamic xml sitemap in asp.net, How to solve password length minimum 7 non alphanumeric characters required 1  and many more about Asp.Net.

Step 1.

Add repeater control to your .aspx page by using following code.

     <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
               <div>
                        <h2>
                            <a href="Default.aspx"><%# Eval("Title") %></a>
                        </h2>
                    </div>
             </ItemTemplate>
        </asp:Repeater>

Here we will retrieve Title from database.  I have title column in table1 from where i will retrieve title.

Step 2.

Also add this code in your .aspx page exactly below the repeater control. This code is for pagination design.

   <table style="width: 600px" border="0" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td colspan="5">
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="center" valign="top" width="80">
                                                <asp:LinkButton ID="lnkFirst" runat="server" OnClick="lnkFirst_Click">First</asp:LinkButton>
                                            </td>
                                            <td align="center" valign="top" width="80">
                                                <asp:LinkButton ID="lnkPrevious" runat="server" OnClick="lnkPrevious_Click">Previous</asp:LinkButton>
                                            </td>
                                            <td align="center">
                                                <asp:DataList ID="RepeaterPaging" runat="server" 
                                                    OnItemCommand="RepeaterPaging_ItemCommand" 
                                                    OnItemDataBound="RepeaterPaging_ItemDataBound" RepeatDirection="Horizontal">
                                                    <ItemTemplate>
                                                        <asp:LinkButton ID="Pagingbtn" runat="server" 
                                                            CommandArgument='<%# Eval("PageIndex") %>' CommandName="newpage" 
                                                            Text='<%# Eval("PageText") %> ' Width="20px"></asp:LinkButton>
                                                    </ItemTemplate>
                                                </asp:DataList>
                                            </td>
                                            <td align="center" valign="top" width="80">
                                                <asp:LinkButton ID="lnkNext" runat="server" OnClick="lnkNext_Click">Next</asp:LinkButton>
                                            </td>
                                            <td align="center" valign="top" width="80">
                                                <asp:LinkButton ID="lnkLast" runat="server" OnClick="lnkLast_Click">Last</asp:LinkButton>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td align="center" valign="top" width="80">
                                                &nbsp;</td>
                                            <td align="center" valign="top" width="80">
                                                &nbsp;</td>
                                            <td align="center">
                                                <asp:Label ID="lblpage" runat="server" Text=""></asp:Label>
                                            </td>
                                            <td align="center" valign="top" width="80">
                                                &nbsp;</td>
                                            <td align="center" valign="top" width="80">
                                                &nbsp;</td>
                                        </tr>
                                    </table>

Step 3.

Write the below code in your .aspx.cs file. Below is your code-behind file.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    PagedDataSource pgsource = new PagedDataSource();
    int findex, lindex;
    DataRow dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
            {
                BindDataList();
            }
        
    }


    DataTable GetData()
    {

        string dbstring = System.Configuration.ConfigurationManager.ConnectionStrings["database_con"].ConnectionString;
        SqlConnection connection = new SqlConnection(dbstring);
        connection.Open();
        SqlDataAdapter cmd = new SqlDataAdapter(" SELECT title from table1", connection);
        DataTable dtable = new DataTable();
        cmd.Fill(dtable);
        connection.Close();
        return dtable;
        
    }

    private void BindDataList()
    {
        //Create new DataTable dt
        DataTable dt = GetData();

        pgsource.DataSource = dt.DefaultView;

        //Set PageDataSource paging 
        pgsource.AllowPaging = true;

        //Set number of items to be displayed in the Repeater using drop down list
      
            pgsource.PageSize = 10;
      

        //Get Current Page Index
        pgsource.CurrentPageIndex = CurrentPage;

        //Store it Total pages value in View state
        ViewState["totpage"] = pgsource.PageCount;

        //Below line is used to show page number based on selection like "Page 1 of 20"
        lblpage.Text = "Page " + (CurrentPage + 1) + " of " + pgsource.PageCount;

        //Enabled true Link button previous when current page is not equal first page 
        //Enabled false Link button previous when current page is first page
        lnkPrevious.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Next when current page is not equal last page 
        //Enabled false Link button Next when current page is last page
        lnkNext.Enabled = !pgsource.IsLastPage;

        //Enabled true Link button First when current page is not equal first page 
        //Enabled false Link button First when current page is first page
        lnkFirst.Enabled = !pgsource.IsFirstPage;

        //Enabled true Link button Last when current page is not equal last page 
        //Enabled false Link button Last when current page is last page
        lnkLast.Enabled = !pgsource.IsLastPage;

        //Bind resulted PageSource into the Repeater
        Repeater1.DataSource = pgsource;
        Repeater1.DataBind();

        //Create Paging with help of DataList control "RepeaterPaging"
        doPaging();
        RepeaterPaging.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
    }

    private void doPaging()
    {
        DataTable dt = new DataTable();
        //Add two column into the DataTable "dt" 
        //First Column store page index default it start from "0"
        //Second Column store page index default it start from "1"
        dt.Columns.Add("PageIndex");
        dt.Columns.Add("PageText");

        //Assign First Index starts from which number in paging data list
        findex = CurrentPage - 5;

        //Set Last index value if current page less than 5 then last index added "5" values to the Current page else it set "10" for last page number
        if (CurrentPage > 5)
        {
            lindex = CurrentPage + 5;
        }
        else
        {
            lindex = 10;
        }

        //Check last page is greater than total page then reduced it to total no. of page is last index
        if (lindex > Convert.ToInt32(ViewState["totpage"]))
        {
            lindex = Convert.ToInt32(ViewState["totpage"]);
            findex = lindex - 10;
        }

        if (findex < 0)
        {
            findex = 0;
        }

        //Now creating page number based on above first and last page index
        for (int i = findex; i < lindex; i++)
        {
            DataRow dr = dt.NewRow();
            dr[0] = i;
            dr[1] = i + 1;
            dt.Rows.Add(dr);
        }

        //Finally bind it page numbers in to the Paging DataList "RepeaterPaging"
        RepeaterPaging.DataSource = dt;
        RepeaterPaging.DataBind();
    }

    private int CurrentPage
    {
        get
        {   //Check view state is null if null then return current index value as "0" else return specific page viewstate value
            if (ViewState["CurrentPage"] == null)
            {
                return 0;
            }
            else
            {
                return ((int)ViewState["CurrentPage"]);
            }
        }
        set
        {
            //Set View statevalue when page is changed through Paging "RepeaterPaging" DataList
            ViewState["CurrentPage"] = value;
        }
    }
    protected void lnkFirst_Click(object sender, EventArgs e)
    {
        //If user click First Link button assign current index as Zero "0" then refresh "Repeater1" Data.
        CurrentPage = 0;
        BindDataList();
    }
    protected void lnkLast_Click(object sender, EventArgs e)
    {
        //If user click Last Link button assign current index as totalpage then refresh "Repeater1" Data.
        CurrentPage = (Convert.ToInt32(ViewState["totpage"]) - 1);
        BindDataList();
    }
    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        //If user click Previous Link button assign current index as -1 it reduce existing page index.
        CurrentPage -= 1;
        //refresh "Repeater1" Data
        BindDataList();
    }
    protected void lnkNext_Click(object sender, EventArgs e)
    {
        //If user click Next Link button assign current index as +1 it add one value to existing page index.
        CurrentPage += 1;

        //refresh "Repeater1" Data
        BindDataList();
    }
    protected void RepeaterPaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
        if (e.CommandName.Equals("newpage"))
        {
            //Assign CurrentPage number when user click on the page number in the Paging "RepeaterPaging" DataList
            CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
            //Refresh "Repeater1" control Data once user change page
            BindDataList();
        }
    }
    protected void RepeaterPaging_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        //Enabled False for current selected Page index
        LinkButton lnkPage = (LinkButton)e.Item.FindControl("Pagingbtn");
        if (lnkPage.CommandArgument.ToString() == CurrentPage.ToString())
        {
            lnkPage.Enabled = false;
            lnkPage.BackColor = System.Drawing.Color.FromName("#FFCC01");
        }
    }
 
}

Step 4.

You are Done.

Step 5.

Debug Your Application. And Make sure you have more than 10 records in your table. So that you are able to test pagination. Below is the Screenshot of pagination.

 

 

Give your Valuable Comments.
comments powered by Disqus
 
Follow me on twitter
About Me
Harpreet Singh
I began programming with C++ when i was 17. Then at the middle of my study .NET came. Then I began to read C# and VB.NET. By the time i learnt SQL and ASP.NET, and developed some websites such as news portals that are active now. Currently i am running my own Software company.
More Articles