Repeater控件分页功能的实现
存在问题:
Repeater是一种常用的动态数据绑定控件,它的布局最为灵活,但有一点很遗憾就是它没有直接实现分页的功能。
解决:
与PageDataSource相结合实现其分页功能。
using System;using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
DataTable table = new DataTable();
PagedDataSource PDS=new PagedDataSource();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
InitData();
}
}
//初始化数据,把数据添加到Session中,避免重复查询数据库。
void InitData()
{
SqlConnection conn = new SqlConnection("Data Source=Localhost;Initial Catalog=Northwind;User ID=sa");
SqlCommand cmm = new SqlCommand("SELECT [CustomerID], [CompanyName] FROM [Customers]");
cmm.Connection = conn;
SqlDataAdapter DA = new SqlDataAdapter();
DA.SelectCommand = cmm;
DataSet DS = new DataSet();
DA.Fill(DS);
table = DS.Tables[0];
if (Session["data"] != null)
{
Session["data"] =table;
}
else
{
Session.Add("data",table);
}
Pagging(0);
}
//实现分页功能
protected void Pagging(int index)
{
PDS.DataSource =((DataTable)Session["data"]).DefaultView;
PDS.CurrentPageIndex = index;
PDS.AllowPaging = true;
PDS.PageSize = 20;
this.Repeater2.DataSource = PDS;
this.Repeater2.DataBind();
DropDownList ddl = (DropDownList)this.Repeater2.Controls[this.Repeater2.Controls.Count - 1].FindControl("PageCount");
if (ddl != null)
{
for (int i = 1; i < PDS.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
}
}
public void PageIndex(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)this.Repeater2.Controls[this.Repeater2.Controls.Count - 1].FindControl("PageCount");
Pagging(int.Parse(ddl.SelectedItem.Text)-1);
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RepeaterPagging.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Repeater分页示例</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater2" runat="server">
<HeaderTemplate >
<div style="width:100%; height:20; color:Green; background-color:Gray;">Repeater分页示例</div>
</HeaderTemplate>
<ItemTemplate>
<table>
<tr>
<td>客户ID:
<label id="id"><%# DataBinder.Eval(Container.DataItem,"CustomerID")%></label>
</td>
<td>公司名称:
<label id="Name"><%# DataBinder.Eval(Container.DataItem,"CompanyName")%></label>
</td>
</tr>
</table>
</ItemTemplate>
<FooterTemplate >
请选择页数
<asp:DropDownList ID="PageCount" AutoPostBack="true" OnTextChanged="PageIndex" runat="server"></asp:DropDownList>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>