AspNet4YouTop 10sDevelopers WorldForums
Home
About
ASPNet Books
ASPNet Sites
ASPNet Hosters
View Articles
Search Articles
Authors
View Forums
 
Quick Menus
HOME
About
AspNet4You Forums
Articles
Authors
Search
Articles Summary
Articles(RSSFeed)
AspNet Books
AspNet Sites
AspNet Hosters
 Top 10 ASP.NET Books 
Professional ASP.NET 1.1
Essential ASP.NET With Examples in C#
ASP.NET Unleashed
Programming Data Driven Web Applications with ASP.NET
Professional ASP.NET Web Services
Beginning ASP.NET 1.1 with Visual C# .NET 2003
Programming Microsoft ASP.NET
Beginning ASP.NET Databases Using VB.NET
ASP.NET Security
Developing Microsoft ASP.NET Server Controls and Components
More...
 Top 10 ASP.NET Hosters 
WebHost4Life
DiscountASP.NET
MaximumASP
Brinkster
ORCS Web
myhosting.com
ISQSolutions
ASPwebhosting.com, LLC
Active ISP
Aquest Hosting
More...
 Top 10 ASP.NET Sites 
Asp.Net
GotDotNet
4GuysFromRolla.com
123aspx.com
EggHeadCafe.com
CShrp.Net
.NET 247
DevelopersDex.com
Csharp-Corner.com
dotnetspider
More...
Search Articles
Google
ASPNET4YOU      
Category:   Search Type:   Match Type:  
How to Implement a Repeater Control with Pagination
Author: Saha, ProdipPosted: 4/23/2005 9:27:32 AM

How to Implement a Repeater Control with Pagination 

Repeater is a data-bound list control that allows custom layout by repeating a specified template for each item displayed in the list. I like the Repeater control because it is the only control that allows the developers to split HTML tags across the templates. This is something you can not do in other data-bound list control like DataGrid. Also, Repeater's performance is faster than  the DataGrid. So, where is the problem? Repeater comes with some limitations. Like the DataGrid it does not have the built-in Paging or Sorting functionality. However, with little extra work we can add the Paging or Sorting functionality to the Repeater and enjoy other benefits. This article will show you how to implement the Paging with Repeater control using PagedDataSource class.

Repeater Live Demo at ASPNET4YOU.COM

Download the complete source code RepeaterExample.zip(25KB)

You can use the PagedDataSource class that encapsulates the properties of the DataGrid control and allow us to perform paging. While there are other properties and methods on the PagedDataSource class we will mostly use the following properties to provide pagination to the Repeater control:

AllowPaging Gets or sets a value indicating whether paging is enabled.
CurrentPageIndex Gets or sets the index of the current page.
DataSource Gets or sets the data source.
IsFirstPage Gets a value indicating whether the current page is the first page.
IsLastPage Gets a value indicating whether the current page is the last page.
PageCount Gets the total number of pages necessary to display all items in the data source.
PageSize Gets or sets the number of items to display on a single page.

CAUTION: You can't use a DataTable object to set the DataSource property of the PagedDataSource class because the DataTable object does not implement an ICollection interface. In this example I have used an Employees collection (collection of Employee class) that inherits from an ArryList.

To get the Repeater control working we need to do three things- define the DataItem in .aspx page, set the DataSource property to a DataTable or to a Collection and call the DataBind method. So where is the trick? The trick is- you set the DataSource property of the Repeater control to an instance of the PagedDataSource class. Ok, we have enough introductions. Let's get to the actual work for that you may be already impatient!

I have created an aspx page -RepeaterPagingExample.aspx with a code behind file RepeaterPagingExample.aspx.cs. It's good practice to separate the data access layer from the presentation layer at least logically. So, I have a class file (DataAccess.cs) to create some data on the fly to keep the example simple. In addition, I have couple of supporting classes (Employees and Employee). You may download the complete source codes at the link provided above.

RepeaterPagingExample.aspx:

<%@ Page language="c#" Codebehind="RepeaterPagingExample.aspx.cs" AutoEventWireup="false" Inherits="ASPNET4YOU.COM.Repeater.RepeaterPagingExample" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
	<HEAD>
		<title>RepeaterPagingExample</title>
		<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
		<meta name="CODE_LANGUAGE" Content="C#">
		<meta name="vs_defaultClientScript" content="JavaScript">
		<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
	</HEAD>
	<body MS_POSITIONING="GridLayout">
		<form id="Form1" method="post" runat="server">
			<table cellSpacing="1" cellPadding="3" width="100%" border="2" align="center">
				<tr>
					<td bgcolor="#99ccff" align="center" style="FONT-WEIGHT: normal; FONT-SIZE: medium; COLOR: black">
						<P>Repeater Live Demo with pagination brought to you by ASPNET4YOU.COM. This proto 
							type is used to build Article page on APNET4YOU.COM. Feel free to extend as it 
							fits your need.</P>
						<P><a href="RepeaterExample.zip"> <FONT style="BACKGROUND-COLOR: #99ccff">Download the 
									complete source code RepeaterExample.zip(25KB)</FONT></a></P>
					</td>
				</tr>
			</table>
			<TABLE cellSpacing="1" cellPadding="3" width="100%" border="2" align="center"> <!--Paging components -->
				<TR>
					<TD class="forumRow" align="center">Page Size:
						<asp:DropDownList id="lstPageSize" Runat="server" AutoPostBack="True">
							<asp:ListItem Value="2">2</asp:ListItem>
							<asp:ListItem Value="5" Selected="True">5</asp:ListItem>
							<asp:ListItem Value="10">10</asp:ListItem>
							<asp:ListItem Value="15">15</asp:ListItem>
							<asp:ListItem Value="20">20</asp:ListItem>
						</asp:DropDownList>  Go to Page:
						<asp:DropDownList id="lstPages" Runat="server" AutoPostBack="True"></asp:DropDownList> of 
						<asp:Label id="lblTotalPages" Runat="server"></asp:Label>   
						<asp:LinkButton id="lnkPrev" Runat="server"><Prev</asp:LinkButton>  
						<asp:LinkButton id="lnkNext" Runat="server">Next></asp:LinkButton></TD>
				</TR> <!--Paging components -->
				<TR>
					<TD>
						<asp:Repeater id="repResults" Runat="server">
							<ItemTemplate>
								<table cellpadding="3" cellspacing="1" width="100%" border="1" align="center">
									<tr>
										<td align="left" bgcolor="#ffffff">
											EmpID: <%# DataBinder.Eval(Container.DataItem, "EmpID") %>
											<br>
											FirstName:<%# DataBinder.Eval(Container.DataItem, "FirstName") %>
											<br>
											LastName:<%# DataBinder.Eval(Container.DataItem, "LastName") %>
											<br>
											HireDate:<%# DataBinder.Eval(Container.DataItem, "HireDate") %>
										</td>
									</tr>
								</table>
							</ItemTemplate>
							<AlternatingItemTemplate>
								<table cellpadding="3" cellspacing="1" width="100%" border="1" align="center">
									<tr>
										<td align="left" bgcolor="#99ccff">
											EmpID: <%# DataBinder.Eval(Container.DataItem, "EmpID") %>
											<br>
											FirstName:<%# DataBinder.Eval(Container.DataItem, "FirstName") %>
											<br>
											LastName:<%# DataBinder.Eval(Container.DataItem, "LastName") %>
											<br>
											HireDate:<%# DataBinder.Eval(Container.DataItem, "HireDate") %>
										</td>
									</tr>
								</table>
							</AlternatingItemTemplate>
						</asp:Repeater>
					</TD>
				</TR>
			</TABLE>
		</form>
	</body>
</HTML>

					

RepeaterPagingExample.aspx.cs:

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace ASPNET4YOU.COM.Repeater
{
	/// 
	/// Summary description for RepeaterPagingExample.
	/// Developed by Prodip K. Saha
	/// This code can be used freely. An acknowledgement to
	/// the ASPNET4YOU.COM will be appreciated though it is not
	/// required.
	/// 
	public class RepeaterPagingExample : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.DropDownList lstPageSize;
		protected System.Web.UI.WebControls.DropDownList lstPages;
		protected System.Web.UI.WebControls.Label lblTotalPages;
		protected System.Web.UI.WebControls.LinkButton lnkPrev;
		protected System.Web.UI.WebControls.LinkButton lnkNext;
		protected System.Web.UI.WebControls.Repeater repResults;
		
		private PagedDataSource pds=new PagedDataSource();
		
		private void Page_Load(object sender, System.EventArgs e)
		{
			
			
			try
			{
				if(!IsPostBack)
				{
					CreateSummary();
					lnkPrev.Visible=(!pds.IsFirstPage);
					lnkNext.Visible=(!pds.IsLastPage);

				}
			}
			catch(Exception ex)
			{
				
			}
					
			
		}
		
		private Employees GetData()
		{
			
			DataAccess data=new DataAccess();
			return data.GetEmployees();

		}

		private void CreateSummary()
		{
						
			//Get Data
			Employees employees=GetData();
			
			//Set paged data source
			pds.DataSource=employees;

			//Do Paging
			SetPaging();
			pds.CurrentPageIndex=0;
			
			//Fill the lstPages dropdown
			lstPages.Items.Clear();
			for(int i=0;i<pds.PageCount;i++)
			{
				lstPages.Items.Add((i+1).ToString());
			}

			//Bind Data
			BindEmployees();

		}

		private void CreateSummaryWithNav()
		{
			
			//Get Data
			Employees employees=GetData();
			
			//Set paged data source
			//PagedDataSource's DataSource MUST be collection that implements ICollection interface
			//to get the pagination working. You are allowed to use a DataTable but it will give you
			//an error when you try to bind the repeater.
			pds.DataSource=employees;

			//Do common Paging
			SetPaging();
			pds.CurrentPageIndex=lstPages.SelectedIndex;

			//Bind Data
			BindEmployees();

		}
		
		private void SetPaging()
		{
			pds.AllowPaging=true;
			pds.PageSize=Int32.Parse(lstPageSize.Items[lstPageSize.SelectedIndex].Value);
			lblTotalPages.Text=pds.PageCount.ToString();


		}
		private void BindEmployees()
		{
			repResults.DataSource=pds;
			repResults.DataBind();
			

			
		}

		private void btnGoPage_Click(object sender, System.EventArgs e)
		{
			
			try
			{
				CreateSummaryWithNav();
				lnkPrev.Visible=(!pds.IsFirstPage);
				lnkNext.Visible=(!pds.IsLastPage);
			}
			catch(Exception ex)
			{
				
			}
		}

		private void lnkPrev_Click(object sender, System.EventArgs e)
		{
			
			try
			{
				if(lstPages.SelectedIndex-1>=0)
				{
					lstPages.SelectedIndex=lstPages.SelectedIndex-1;
					CreateSummaryWithNav();
				}
				lnkPrev.Visible=(!pds.IsFirstPage);
				lnkNext.Visible=(!pds.IsLastPage);
			}
			catch(Exception ex)
			{
				
			}
		}

		private void lnkNext_Click(object sender, System.EventArgs e)
		{
			
			try
			{
				if(lstPages.SelectedIndex+1<lstPages.Items.Count)
				{
					lstPages.SelectedIndex=lstPages.SelectedIndex+1;
					CreateSummaryWithNav();
				}
				lnkPrev.Visible=(!pds.IsFirstPage);
				lnkNext.Visible=(!pds.IsLastPage);
			}
			catch(Exception ex)
			{
				
			}
		}

		private void lstPageSize_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			
			try
			{
				CreateSummary();
				lnkPrev.Visible=(!pds.IsFirstPage);
				lnkNext.Visible=(!pds.IsLastPage);
			}
			catch(Exception ex)
			{
				
			}
		}

		private void lstPages_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			
			try
			{
				CreateSummaryWithNav();
				lnkPrev.Visible=(!pds.IsFirstPage);
				lnkNext.Visible=(!pds.IsLastPage);
			}
			catch(Exception ex)
			{
				
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// 
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// 
		private void InitializeComponent()
		{    
			this.lstPageSize.SelectedIndexChanged += new System.EventHandler(this.lstPageSize_SelectedIndexChanged);
			this.lstPages.SelectedIndexChanged += new System.EventHandler(this.lstPages_SelectedIndexChanged);
			this.lnkPrev.Click += new System.EventHandler(this.lnkPrev_Click);
			this.lnkNext.Click += new System.EventHandler(this.lnkNext_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
	}
}

					

DataAccess.cs:

using System;
using System.Data;

namespace ASPNET4YOU.COM.Repeater
{
	/// 
	/// Summary description for DataAccess.
	/// 
	public class DataAccess
	{
		public DataAccess()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public static DataTable GetDummyData()
		{
			//This method creates a datatable on the fly
			//and add some dummy records in it. In real world
			//one should be connecting to a database to retrive
			//the data.

			//Create a new table object
			DataTable dtTemp=new DataTable("Employees");

			//Add some columns
			dtTemp.Columns.Add("EmpID",Type.GetType("System.Int32"));
			dtTemp.Columns.Add("FirstName",Type.GetType("System.String"));
			dtTemp.Columns.Add("LastName",Type.GetType("System.String"));
			dtTemp.Columns.Add("HireDate",Type.GetType("System.DateTime"));

			//Add some rows
			DataRow dr;
			dr=dtTemp.NewRow(); //add a new row with a schema same as the table schema
			dr["EmpID"]=1;
			dr["FirstName"]="Joe";
			dr["LastName"]="Long";
			dr["HireDate"]="01/01/1999";
			dtTemp.Rows.Add(dr); //insert the row in the table

			dr=dtTemp.NewRow();
			dr["EmpID"]=2;
			dr["FirstName"]="Sherry";
			dr["LastName"]="Park";
			dr["HireDate"]="01/13/2002";
			dtTemp.Rows.Add(dr);
			
			dr=dtTemp.NewRow();
			dr["EmpID"]=3;
			dr["FirstName"]="Peter";
			dr["LastName"]="Clark";
			dr["HireDate"]="12/23/2003";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=4;
			dr["FirstName"]="Cindy";
			dr["LastName"]="Jones";
			dr["HireDate"]="09/24/1998";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=5;
			dr["FirstName"]="Tina";
			dr["LastName"]="Matinez";
			dr["HireDate"]="11/29/2000";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=6;
			dr["FirstName"]="Jose";
			dr["LastName"]="Mario";
			dr["HireDate"]="05/29/2001";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=7;
			dr["FirstName"]="Walter";
			dr["LastName"]="Barios";
			dr["HireDate"]="01/05/2002";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=8;
			dr["FirstName"]="Cindy";
			dr["LastName"]="Jones";
			dr["HireDate"]="01/05/2003";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=9;
			dr["FirstName"]="Tom";
			dr["LastName"]="Happy";
			dr["HireDate"]="01/05/2004";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=10;
			dr["FirstName"]="Jody";
			dr["LastName"]="Lane";
			dr["HireDate"]="04/01/2001";
			dtTemp.Rows.Add(dr);

			dr=dtTemp.NewRow();
			dr["EmpID"]=11;
			dr["FirstName"]="Tory";
			dr["LastName"]="Hersh";
			dr["HireDate"]="09/12/2004";
			dtTemp.Rows.Add(dr);

			
			return dtTemp;
			
		}
		
		public Employees GetEmployees()
		{
			Employees employees=new Employees();
			Employee emp;

			DataTable dtEmp=DataAccess.GetDummyData();

			foreach(DataRow dr in dtEmp.Rows)
			{
				emp=new Employee();
				emp.EmpID=Int32.Parse(dr["EmpID"].ToString());
				emp.FirstName=dr["FirstName"].ToString();
				emp.LastName=dr["LastName"].ToString();
				emp.HireDate=dr["HireDate"].ToString();
				employees.Add(emp);

			}

			return employees;
		}

	}
}

					

Employees.cs:

using System;
using System.Collections;

namespace ASPNET4YOU.COM.Repeater
{
	/// 
	/// Summary description for Employees.
	/// 
	public class Employees:ArrayList
	{
		public Employees():base(){}
		public Employees(ICollection c):base(c){}
	}
}

					

Employee.cs:

using System;

namespace ASPNET4YOU.COM.Repeater
{
	/// 
	/// Summary description for Employee.
	/// 
	public class Employee
	{
		private int _EmpID=0;
		private string _FirstName="";
		private string _LastName="";
		private string _HireDate="";


		public Employee()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public int EmpID
		{
			get{return _EmpID;}
			set{_EmpID=value;}
		}

		public string FirstName
		{
			get{return _FirstName;}
			set{_FirstName=value;}
		}

		public string LastName
		{
			get{return _LastName;}
			set{_LastName=value;}
		}
		
		public string HireDate
		{
			get{return _HireDate;}
			set{_HireDate=value;}
		}


	}
}

					

 


Prodip K. Saha
The Architect of WWW.ASPNET4YOU.COM.

Terms and Conditions