自定义datalist分页(转)
DataList Web 服务器控件以某种格式显示数据,这种格式可以使用模板和样式进行定义。DataList 控件可用于任何重复结构中的数据,如表。DataList 控件可以以不同的布局显示行,如按列或行对数据进行排序。DataList 控件不能自动利用数据源控件的更新功能以及自动分页或排序。若要使用 DataList 控件执行更新、分页和排序,必须在编写的代码中执行更新任务。
在PetShop4.0中,有一个叫做CustomList的类引起了我们的注意,它继承了DataList类,并对其进行了改写,实现了分页功能,然而,PetShop4.0中对分页功能较简单(只有上下翻页功能),本文介绍PetShop4.0中DataList类的改写思路,并对其进行进一步的研究。
一、效果图
这个效果图比较粗糙,读者可以根据自己的需要,对其进行改写。
二、具体改写的代码
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomList {
public class CustomList : DataList {
//Static constants
private string HTML1 = "<table cellpadding=0 cellspacing=0 ><tr><td colspan=13>";
protected const string HTML2 = "</td></tr><tr>";
protected const string HTML4 = "</tr></table>";
private static readonly Regex RX = new Regex(@"^&page=d+", RegexOptions.Compiled);
private const string LINK_PREV = "<td><a href=?page={0}> 上一页</a></td>";
private const string LINK_MORE = "<td><a href=?page={0}>下一页 </a></td>";
private const string LINK_DISPLAY = "<td><a href=?page={0}> {1} </a></td>";
private const string KEY_PAGE = "page";
private const string COMMA = "?";
private const string AMP = "&";
protected string emptyText;
private IList dataSource;
private int pageSize = 10;
private int currentPageIndex;
private int itemCount;
override public object DataSource {
set {
//This try catch block is to avoid issues with the VS.NET designer
//The designer will try and bind a datasource which does not derive from ILIST
try {
dataSource = (IList)value;
ItemCount = dataSource.Count;
}
catch {
dataSource = null;
ItemCount = 0;
}
}
}
public int PageSize {
get { return pageSize; }
set { pageSize = value; }
}
protected int PageCount {
get { return (ItemCount - 1) / pageSize; }
}
virtual protected int ItemCount {
get { return itemCount; }
set { itemCount = value; }
}
virtual public int CurrentPageIndex {
get { return currentPageIndex; }
set { currentPageIndex = value; }
}
public string EmptyText {
set { emptyText = value; }
}
public void SetPage(int index) {
OnPageIndexChanged(new DataGridPageChangedEventArgs(null, index));
}
override protected void OnLoad(EventArgs e) {
if (Visible) {
string page = Context.Request[KEY_PAGE];
int index = (page != null) ? int.Parse(page)-1 : 0;
SetPage(index);
}
}
/// <summary>
/// Overriden method to control how the page is rendered
/// </summary>
/// <param name="writer"></param>
override protected void Render(HtmlTextWriter writer) {
//Check there is some data attached
if (ItemCount == 0) {
writer.Write(emptyText);
return;
}
//Mask the query
string query = Context.Request.Url.Query.Replace(COMMA, AMP);
query = RX.Replace(query, string.Empty);
// Write out the first part of the control, the table header
writer.Write(HTML1);
// Call the inherited method
base.Render(writer);
// Write out a table row closure
writer.Write(HTML2);
//列表信息
writer.Write("<td>共 " + PageCount + " 页 " + itemCount + " 项</td>");
//导航到上一页
if (currentPageIndex > 0)
writer.Write(string.Format(LINK_PREV, (currentPageIndex ) + query));
else
{
writer.Write("<td> 上一页 </td>");
}
//得到页码导航
for (int i =0; i <= 9 && i <= PageCount && (currentPageIndex - currentPageIndex % 10 + i)<=PageCount ; i++)
{
if (currentPageIndex - currentPageIndex % 10 + i == currentPageIndex)
{
writer.Write("<td> " + (currentPageIndex+1) + " </td>");
}
else
{
writer.Write(string.Format(LINK_DISPLAY, (currentPageIndex - currentPageIndex % 10 + i+1) + query,(currentPageIndex - currentPageIndex % 10 + i+1) ));
}
}
//导航到下一页
if (currentPageIndex < PageCount)
writer.Write(string.Format(LINK_MORE, (currentPageIndex + 2) + query));
else
{
writer.Write("<td> 下一页 </td>");
}
//Close the table
writer.Write(HTML4);
}
override protected void OnDataBinding(EventArgs e) {
//Work out which items we want to render to the page
int start = CurrentPageIndex * pageSize;
int size = Math.Min(pageSize, ItemCount - start);
IList page = new ArrayList();
//Add the relevant items from the datasource
for (int i = 0; i < size; i++)
page.Add(dataSource[start + i]);
//set the base objects datasource
base.DataSource = page;
base.OnDataBinding(e);
}
public event DataGridPageChangedEventHandler PageIndexChanged;
virtual protected void OnPageIndexChanged(DataGridPageChangedEventArgs e) {
if (PageIndexChanged != null)
PageIndexChanged(this, e);
}
}
}
using System.Collections;
using System.Collections.Specialized;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace CustomList {
public class CustomList : DataList {
//Static constants
private string HTML1 = "<table cellpadding=0 cellspacing=0 ><tr><td colspan=13>";
protected const string HTML2 = "</td></tr><tr>";
protected const string HTML4 = "</tr></table>";
private static readonly Regex RX = new Regex(@"^&page=d+", RegexOptions.Compiled);
private const string LINK_PREV = "<td><a href=?page={0}> 上一页</a></td>";
private const string LINK_MORE = "<td><a href=?page={0}>下一页 </a></td>";
private const string LINK_DISPLAY = "<td><a href=?page={0}> {1} </a></td>";
private const string KEY_PAGE = "page";
private const string COMMA = "?";
private const string AMP = "&";
protected string emptyText;
private IList dataSource;
private int pageSize = 10;
private int currentPageIndex;
private int itemCount;
override public object DataSource {
set {
//This try catch block is to avoid issues with the VS.NET designer
//The designer will try and bind a datasource which does not derive from ILIST
try {
dataSource = (IList)value;
ItemCount = dataSource.Count;
}
catch {
dataSource = null;
ItemCount = 0;
}
}
}
public int PageSize {
get { return pageSize; }
set { pageSize = value; }
}
protected int PageCount {
get { return (ItemCount - 1) / pageSize; }
}
virtual protected int ItemCount {
get { return itemCount; }
set { itemCount = value; }
}
virtual public int CurrentPageIndex {
get { return currentPageIndex; }
set { currentPageIndex = value; }
}
public string EmptyText {
set { emptyText = value; }
}
public void SetPage(int index) {
OnPageIndexChanged(new DataGridPageChangedEventArgs(null, index));
}
override protected void OnLoad(EventArgs e) {
if (Visible) {
string page = Context.Request[KEY_PAGE];
int index = (page != null) ? int.Parse(page)-1 : 0;
SetPage(index);
}
}
/// <summary>
/// Overriden method to control how the page is rendered
/// </summary>
/// <param name="writer"></param>
override protected void Render(HtmlTextWriter writer) {
//Check there is some data attached
if (ItemCount == 0) {
writer.Write(emptyText);
return;
}
//Mask the query
string query = Context.Request.Url.Query.Replace(COMMA, AMP);
query = RX.Replace(query, string.Empty);
// Write out the first part of the control, the table header
writer.Write(HTML1);
// Call the inherited method
base.Render(writer);
// Write out a table row closure
writer.Write(HTML2);
//列表信息
writer.Write("<td>共 " + PageCount + " 页 " + itemCount + " 项</td>");
//导航到上一页
if (currentPageIndex > 0)
writer.Write(string.Format(LINK_PREV, (currentPageIndex ) + query));
else
{
writer.Write("<td> 上一页 </td>");
}
//得到页码导航
for (int i =0; i <= 9 && i <= PageCount && (currentPageIndex - currentPageIndex % 10 + i)<=PageCount ; i++)
{
if (currentPageIndex - currentPageIndex % 10 + i == currentPageIndex)
{
writer.Write("<td> " + (currentPageIndex+1) + " </td>");
}
else
{
writer.Write(string.Format(LINK_DISPLAY, (currentPageIndex - currentPageIndex % 10 + i+1) + query,(currentPageIndex - currentPageIndex % 10 + i+1) ));
}
}
//导航到下一页
if (currentPageIndex < PageCount)
writer.Write(string.Format(LINK_MORE, (currentPageIndex + 2) + query));
else
{
writer.Write("<td> 下一页 </td>");
}
//Close the table
writer.Write(HTML4);
}
override protected void OnDataBinding(EventArgs e) {
//Work out which items we want to render to the page
int start = CurrentPageIndex * pageSize;
int size = Math.Min(pageSize, ItemCount - start);
IList page = new ArrayList();
//Add the relevant items from the datasource
for (int i = 0; i < size; i++)
page.Add(dataSource[start + i]);
//set the base objects datasource
base.DataSource = page;
base.OnDataBinding(e);
}
public event DataGridPageChangedEventHandler PageIndexChanged;
virtual protected void OnPageIndexChanged(DataGridPageChangedEventArgs e) {
if (PageIndexChanged != null)
PageIndexChanged(this, e);
}
}
}
三、新建一个类库工程,把上面代码保存为CustomList.cs,再重新生成,在工具栏便会多出一个用户自定义组件。
四、对其进行调用
1.新建网站,在新页面中拖拽一个CustomList组件。
2.对CustomList组件进行前台属性设置
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="CustomList" Namespace="CustomList" TagPrefix="cc1" %>
<!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>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<cc1:CustomList ID="productsList" runat="server" EmptyText="No products found." OnPageIndexChanged="PageChanged" PageSize="12" RepeatColumns="1" CellPadding="4" Width="400px" CurrentPageIndex="1" ForeColor="#333333">
<ItemTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<td valign="top" width="400px" align="center" ><%# Eval("dc")%></td>
</tr>
</table>
</ItemTemplate>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<AlternatingItemStyle BackColor="White" />
<ItemStyle BackColor="#FFFBD6" ForeColor="#333333" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
</cc1:CustomList>
</form>
</body>
</html>
<%@ Register Assembly="CustomList" Namespace="CustomList" TagPrefix="cc1" %>
<!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>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<cc1:CustomList ID="productsList" runat="server" EmptyText="No products found." OnPageIndexChanged="PageChanged" PageSize="12" RepeatColumns="1" CellPadding="4" Width="400px" CurrentPageIndex="1" ForeColor="#333333">
<ItemTemplate>
<table cellpadding="0" cellspacing="0">
<tr>
<td valign="top" width="400px" align="center" ><%# Eval("dc")%></td>
</tr>
</table>
</ItemTemplate>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<AlternatingItemStyle BackColor="White" />
<ItemStyle BackColor="#FFFBD6" ForeColor="#333333" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
</cc1:CustomList>
</form>
</body>
</html>
22.后台页面程序绑定
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.Collections;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
{
//reset index
productsList.CurrentPageIndex = e.NewPageIndex;
//构造要作为数据源显示的表
DataTable dt = new DataTable("tabe1");
DataColumn dc = new DataColumn("dc");
dt.Columns.Add(dc);//构造一列
for (int i = 1; i <= 100; i++)//循环加入数据
{
DataRow dr = dt.NewRow();
dr["dc"] ="数据"+ i;
dt.Rows.Add(dr);
}
//bind data
productsList.DataSource = dt.DefaultView;
productsList.DataBind();
}
}
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.Collections;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void PageChanged(object sender, DataGridPageChangedEventArgs e)
{
//reset index
productsList.CurrentPageIndex = e.NewPageIndex;
//构造要作为数据源显示的表
DataTable dt = new DataTable("tabe1");
DataColumn dc = new DataColumn("dc");
dt.Columns.Add(dc);//构造一列
for (int i = 1; i <= 100; i++)//循环加入数据
{
DataRow dr = dt.NewRow();
dr["dc"] ="数据"+ i;
dt.Rows.Add(dr);
}
//bind data
productsList.DataSource = dt.DefaultView;
productsList.DataBind();
}
}
Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1669427