Introduction
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:
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,
CONSTRAINT [PK_tblPerson] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
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.
<connectionStrings>
<add name="stringConnection" connectionString="Data Source = CHIENVH-PC;
Initial Catalog=MyDB;Persist Security Info=True;User ID=sa; Password=123456789;"/>
</connectionStrings>
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="http://www.w3.org/1999/xhtml">
<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;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="MainScriptManager" runat="server" />
<asp:UpdatePanel ID="pnlHelloWorld" runat="server">
<ContentTemplate>
<div>
<asp:Repeater ID="rptResult" runat="server">
<HeaderTemplate>
<table class="auto-style1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Created Date</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><%#Eval("Id") %></td>
<td><%#Eval("Name") %></td>
<td><%#Eval("Address") %></td>
<td><%#Eval("createdDate") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
<div style="margin-top: 20px;">
<table style="width: 600px;">
<tr>
<td>
<asp:LinkButton ID="lbFirst" runat="server"
OnClick="lbFirst_Click">First</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lbPrevious" runat="server"
OnClick="lbPrevious_Click">Previous</asp:LinkButton>
</td>
<td>
<asp:DataList ID="rptPaging" runat="server"
OnItemCommand="rptPaging_ItemCommand"
OnItemDataBound="rptPaging_ItemDataBound"
RepeatDirection="Horizontal">
<ItemTemplate>
<asp:LinkButton ID="lbPaging" runat="server"
CommandArgument='<%# Eval("PageIndex") %>'
CommandName="newPage"
Text='<%# Eval("PageText") %> ' Width="20px">
</asp:LinkButton>
</ItemTemplate>
</asp:DataList>
</td>
<td>
<asp:LinkButton ID="lbNext" runat="server"
OnClick="lbNext_Click">Next</asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="lbLast" runat="server"
OnClick="lbLast_Click">Last</asp:LinkButton>
</td>
<td>
<asp:Label ID="lblpage" runat="server" Text=""></asp:Label>
</td>
</tr>
</table>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
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
{
get
{
if (ViewState["CurrentPage"] == null)
{
return 0;
}
return ((int)ViewState["CurrentPage"]);
}
set
{
ViewState["CurrentPage"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack) return;
BindDataIntoRepeater();
}
static DataTable GetDataFromDb()
{
var con = new SqlConnection(ConfigurationManager.ConnectionStrings
["stringConnection"].ToString());
con.Open();
var da = new SqlDataAdapter("Select Id, Name, Address,
CreatedDate From tblPerson Order By Id desc", con);
var dt = new DataTable();
da.Fill(dt);
con.Close();
return dt;
}
private void BindDataIntoRepeater()
{
var dt = GetDataFromDb();
_pgsource.DataSource = dt.DefaultView;
_pgsource.AllowPaging = true;
_pgsource.PageSize = _pageSize;
_pgsource.CurrentPageIndex = CurrentPage;
ViewState["TotalPages"] = _pgsource.PageCount;
lblpage.Text = "Page " + (CurrentPage + 1) + " of " + _pgsource.PageCount;
lbPrevious.Enabled = !_pgsource.IsFirstPage;
lbNext.Enabled = !_pgsource.IsLastPage;
lbFirst.Enabled = !_pgsource.IsFirstPage;
lbLast.Enabled = !_pgsource.IsLastPage;
rptResult.DataSource = _pgsource;
rptResult.DataBind();
HandlePaging();
}
private void HandlePaging()
{
var dt = new DataTable();
dt.Columns.Add("PageIndex"); dt.Columns.Add("PageText");
_firstIndex = CurrentPage - 5;
if (CurrentPage > 5)
_lastIndex = CurrentPage + 5;
else
_lastIndex = 10;
if (_lastIndex > Convert.ToInt32(ViewState["TotalPages"]))
{
_lastIndex = Convert.ToInt32(ViewState["TotalPages"]);
_firstIndex = _lastIndex - 10;
}
if (_firstIndex < 0)
_firstIndex = 0;
for (var i = _firstIndex; i < _lastIndex; i++)
{
var dr = dt.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt.Rows.Add(dr);
}
rptPaging.DataSource = dt;
rptPaging.DataBind();
}
protected void lbFirst_Click(object sender, EventArgs e)
{
CurrentPage = 0;
BindDataIntoRepeater();
}
protected void lbLast_Click(object sender, EventArgs e)
{
CurrentPage = (Convert.ToInt32(ViewState["TotalPages"]) - 1);
BindDataIntoRepeater();
}
protected void lbPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
BindDataIntoRepeater();
}
protected void lbNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
BindDataIntoRepeater();
}
protected void rptPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (!e.CommandName.Equals("newPage")) return;
CurrentPage = Convert.ToInt32(e.CommandArgument.ToString());
BindDataIntoRepeater();
}
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.
History
- Sunday, October 11, 2015: Initial version