分頁是Web應用程序中最常用到的功能之一,在ASP.NET中,雖然自帶了一些可以分頁的數據控件,但其分頁功能並不盡如人意。本文對於這些數據控件的假分頁暫且不表,如有不明白的同學請百Google度之。
本文中實現的分頁控件是在手動分頁基礎上做的改善,將分頁實現的邏輯部分和數據控件的綁定盡可能分開,以克服手工編寫分頁代碼任務繁瑣、代碼重用率低等問題。
本文依舊是一粒粟子。
一、分頁控件素顏
二、分頁控件的實現
本文中將介紹兩種將分頁實現邏輯與數據控件綁定分離的實現方式:
- 使用反射機制
- 使用事件機制
1、基於反射機制的分頁控件
源碼:
PagingHelper.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PagingHelper.ascx.cs" Inherits="PagingHelper.Controls.PagingHelper" %>
<div style="width:100%">
<asp:LinkButton ID="lbtnFirstPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >首頁</asp:LinkButton>
<asp:LinkButton ID="lbtnPrevPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >上一頁</asp:LinkButton>
第<asp:Label ID="lbPageIndex" runat="server" Text=""></asp:Label>
頁/共<asp:Label ID="lbTotalPages" runat="server" Text=""></asp:Label>
頁
<asp:LinkButton ID="lbtnNextPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >下一頁</asp:LinkButton>
<asp:LinkButton ID="lbtnLastPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >尾頁</asp:LinkButton>
</div>
PagingHelper.ascx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Reflection;
namespace PagingHelper.Controls
{
public partial class PagingHelper : System.Web.UI.UserControl
{
#region 屬性
private int m_PageSize;
public int PageSize //每頁顯示記錄數
{
set
{
m_PageSize = value;
}
get
{
if (m_PageSize.Equals(0))
{
m_PageSize = 10;
}
return m_PageSize;
}
}
private int m_PageIndex;
public int PageIndex //當前頁頁碼
{
set
{
m_PageIndex = value;
}
get
{
if (m_PageIndex.Equals(0))
{
m_PageIndex = 1;
}
return m_PageIndex;
}
}
public int TotalItemCount //記錄總數
{
set;
private get;
}
public string BindDataMethodName //綁定數據的方法名
{
set;
private get;
}
#endregion
#region 受保護的方法
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPagingHelperControl();
}
}
protected void lbtnPage_Click(object sender, EventArgs e)
{
LinkButton lbtn = sender as LinkButton;
ReBindData(lbtn.CommandArgument);
}
#endregion
#region 公共方法
#endregion
#region 私有方法
private void BindPagingHelperControl()
{
int totalPages = (TotalItemCount % PageSize) == 0 ? TotalItemCount / PageSize : TotalItemCount / PageSize + 1;
//顯示
lbPageIndex.Text = PageIndex.ToString();
lbTotalPages.Text = totalPages.ToString();
//使能
lbtnFirstPage.Enabled = PageIndex > 1;
lbtnPrevPage.Enabled = PageIndex > 1;
lbtnLastPage.Enabled = PageIndex < totalPages;
lbtnNextPage.Enabled = PageIndex < totalPages;
//命令
lbtnFirstPage.CommandArgument = "1";
lbtnPrevPage.CommandArgument = (PageIndex - 1).ToString();
lbtnNextPage.CommandArgument = (PageIndex + 1).ToString();
lbtnLastPage.CommandArgument = totalPages.ToString();
}
private void ReBindData(string pageIndex)
{
PageIndex = int.Parse(pageIndex);
Object obj = null; //空間所在的容器
if (base.Parent is HtmlForm)
{
obj = this.Page;
}
else if (base.Parent is ContentPlaceHolder)
{
obj = this.Page.Master.Page;
}
else
{
obj = base.Parent;
}
MethodInfo methodInfo = obj.GetType().GetMethod(BindDataMethodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
methodInfo.Invoke(obj, null);
BindPagingHelperControl();
}
#endregion
}
}
Demo:
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PagingHelper.Default" %>
<%@ Register src="Controls/PagingHelper.ascx" tagname="PagingHelper" tagprefix="uc1" %>
<!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">
<div>
<asp:GridView ID="gvDemo" runat="server">
</asp:GridView>
<br />
<uc1:PagingHelper ID="PagingHelper1" runat="server" PageSize="2" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
namespace PagingHelper
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GvDemoBind();
}
protected void GvDemoBind()
{
string sql = @"SELECT * FROM tb_user";
string sqlCount = @"SELECT COUNT(*) FROM tb_user ";
int itemStart = (PagingHelper1.PageIndex - 1) * PagingHelper1.PageSize;
sql += string.Format(" LIMIT {0},{1}",itemStart,PagingHelper1.PageSize);
gvDemo.DataSource = SQLHelper.ExecuteDataTable(sql).DefaultView;
gvDemo.DataBind();
PagingHelper1.TotalItemCount = Convert.ToInt32(SQLHelper.ExecuteScalar(sqlCount));
PagingHelper1.BindDataMethodName = "GvDemoBind";
}
}
}
2、基於事件機制的分頁控件
源碼:
PagingHelper.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PagingHelper.ascx.cs" Inherits="PagingHelper_V2.Controls.PagingHelper" %>
<div style="width:100%">
<asp:LinkButton ID="lbtnFirstPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >首頁</asp:LinkButton>
<asp:LinkButton ID="lbtnPrevPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >上一頁</asp:LinkButton>
第<asp:Label ID="lbPageIndex" runat="server" Text=""></asp:Label>
頁/共<asp:Label ID="lbTotalPages" runat="server" Text=""></asp:Label>
頁
<asp:LinkButton ID="lbtnNextPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >下一頁</asp:LinkButton>
<asp:LinkButton ID="lbtnLastPage" runat="server" CausesValidation="false" onclick="lbtnPage_Click" >尾頁</asp:LinkButton>
轉到
<asp:TextBox ID="txtGoto" runat="server" Width="32px"></asp:TextBox>
頁<asp:Button ID="btnGoto" runat="server" Text="確定" onclick="btnGoto_Click" />
</div>
PagingHelper.ascx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace PagingHelper_V2.Controls
{
public partial class PagingHelper : System.Web.UI.UserControl
{
#region 屬性
private int m_PageSize;
public int PageSize //每頁顯示記錄數
{
set
{
m_PageSize = value;
}
get
{
if (m_PageSize.Equals(0))
{
m_PageSize = 10;
}
return m_PageSize;
}
}
private int m_PageIndex;
public int PageIndex //當前頁頁碼
{
set
{
m_PageIndex = value;
}
get
{
if (m_PageIndex.Equals(0))
{
m_PageIndex = 1;
}
return m_PageIndex;
}
}
public int TotalItemCount //記錄總數
{
set;
private get;
}
#endregion
#region 受保護的方法
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPagingHelperControl();
}
}
protected void lbtnPage_Click(object sender, EventArgs e)
{
LinkButton lbtn = sender as LinkButton;
ReBindData(int.Parse(lbtn.CommandArgument));
}
protected void btnGoto_Click(object sender, EventArgs e)
{
int gotoPageIndex = PageIndex;
if (int.TryParse(txtGoto.Text, out gotoPageIndex))
{
if (gotoPageIndex < 1 || gotoPageIndex > int.Parse(lbTotalPages.Text))
{
Response.Write("<script>alert('此頁面不存在!')</script>");
}
else
{
if (!gotoPageIndex.Equals(int.Parse(lbPageIndex.Text)))
{
ReBindData(gotoPageIndex);
}
}
}
else
{
Response.Write("<script>alert('請輸入正確的頁碼!')</script>");
}
}
#endregion
#region 公共方法
#endregion
#region 私有方法
private void BindPagingHelperControl()
{
int totalPages = (TotalItemCount % PageSize) == 0 ? TotalItemCount / PageSize : TotalItemCount / PageSize + 1;
//顯示
lbPageIndex.Text = PageIndex.ToString();
lbTotalPages.Text = totalPages.ToString();
txtGoto.Text = PageIndex.ToString();
//使能
lbtnFirstPage.Enabled = PageIndex > 1;
lbtnPrevPage.Enabled = PageIndex > 1;
lbtnLastPage.Enabled = PageIndex < totalPages;
lbtnNextPage.Enabled = PageIndex < totalPages;
//命令
lbtnFirstPage.CommandArgument = "1";
lbtnPrevPage.CommandArgument = (PageIndex - 1).ToString();
lbtnNextPage.CommandArgument = (PageIndex + 1).ToString();
lbtnLastPage.CommandArgument = totalPages.ToString();
}
private void ReBindData(int pageIndex)
{
PageIndex = pageIndex;
OnPageIndexChanged(new EventArgs());
BindPagingHelperControl();
}
#endregion
#region 事件
public delegate void PageIndexChangedEventHandler(object sender, EventArgs e);
public event PageIndexChangedEventHandler PageIndexChanged;
protected virtual void OnPageIndexChanged(EventArgs e)
{
PageIndexChangedEventHandler handler = PageIndexChanged;
if (handler != null)
{
handler(this, e);
}
}
#endregion
}
}
Demo:
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PagingHelper_V2.Default" %>
<%@ Register src="Controls/PagingHelper.ascx" tagname="PagingHelper" tagprefix="uc1" %>
<!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">
<div>
<asp:GridView ID="gvDemo" runat="server">
</asp:GridView>
<uc1:PagingHelper ID="PagingHelper1" runat="server" PageSize="2" OnPageIndexChanged="PagingHelper1_OnPageIndexChanged" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PagingHelper_V2
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GvDemoBind();
}
protected void GvDemoBind()
{
string sql = @"SELECT * FROM tb_user";
string sqlCount = @"SELECT COUNT(*) FROM tb_user ";
int itemStart = (PagingHelper1.PageIndex - 1) * PagingHelper1.PageSize;
sql += string.Format(" LIMIT {0},{1}", itemStart, PagingHelper1.PageSize);
gvDemo.DataSource = SQLHelper.ExecuteDataTable(sql).DefaultView;
gvDemo.DataBind();
PagingHelper1.TotalItemCount = Convert.ToInt32(SQLHelper.ExecuteScalar(sqlCount));
}
protected void PagingHelper1_OnPageIndexChanged(object sender, EventArgs e)
{
GvDemoBind();
}
}
}
三、總結
比較兩種實現方式,基於事件機制的實現更符合ASP.NET服務器控件的style。
好!那就參照園子里的分頁使用基於事件機制的方式再做一個控件作為總結。
源碼:
PagingHelper.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PagingHelper.ascx.cs" Inherits="PagingHelper_V3.Controls.PagingHelper" %>
<style type="text/css">
a.LinkButtonDefault{text-align:center;text-decoration:none;margin-right:1px;padding:2px 4px;}
a.LinkButtonBlue{background: #ebebeb;text-align:center;text-decoration:none;margin-right:1px;padding:2px 4px;}
a.LinkButtonYellow { background-color:#ccc; color:#000fff; font-weight:bold;text-align:center;text-decoration:none;margin-right:1px;padding:2px 4px;}
</style>
<div style="width:100%">
共<asp:Label ID="lbTotalPages" runat="server" ForeColor="#fff"></asp:Label>頁:
<asp:LinkButton ID="lbtnFirstPage" runat="server" CausesValidation="false" CssClass="LinkButtonDefault" onclick="lbtnPage_Click" >首頁</asp:LinkButton>
<asp:LinkButton ID="lbtnPrevPage" runat="server" CausesValidation="false" CssClass="LinkButtonDefault" onclick="lbtnPage_Click" >上一頁</asp:LinkButton>
<asp:Repeater ID="rptPageNumber" runat="server">
<ItemTemplate>
<asp:LinkButton ID="lbtnPageNumber" runat="server" CausesValidation="false" Width="16px" onclick="lbtnPage_Click"
CssClass='<%# Convert.ToInt32(Container.DataItem)==PageIndex?"LinkButtonYellow":"LinkButtonBlue"%>' CommandArgument='<%# Container.DataItem %>'>
<%
1: #Container.DataItem
%>
</asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
<asp:LinkButton ID="lbtnNextPage" runat="server" CausesValidation="false" CssClass="LinkButtonDefault" onclick="lbtnPage_Click" >下一頁</asp:LinkButton>
<asp:LinkButton ID="lbtnLastPage" runat="server" CausesValidation="false" CssClass="LinkButtonDefault" onclick="lbtnPage_Click" >尾頁</asp:LinkButton>
</div>
PagingHelper.ascx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace PagingHelper_V3.Controls
{
public partial class PagingHelper : System.Web.UI.UserControl
{
#region 屬性
private int m_PageSize;
public int PageSize //每頁顯示記錄數
{
set
{
m_PageSize = value;
}
get
{
if (m_PageSize.Equals(0))
{
m_PageSize = 10;
}
return m_PageSize;
}
}
private int m_PageIndex;
public int PageIndex //當前頁頁碼
{
set
{
m_PageIndex = value;
}
get
{
if (m_PageIndex.Equals(0))
{
m_PageIndex = 1;
}
return m_PageIndex;
}
}
public int TotalItemCount //記錄總數
{
set;
private get;
}
#endregion
#region 受保護的方法
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindPagingHelperControl();
}
}
protected void lbtnPage_Click(object sender, EventArgs e)
{
LinkButton lbtn = sender as LinkButton;
ReBindData(int.Parse(lbtn.CommandArgument));
}
#endregion
#region 公共方法
#endregion
#region 私有方法
private void BindPageNum(int totalPages)
{
int startPageIndex = 1, endPageIndex = 10;
if (totalPages < endPageIndex)
{
endPageIndex = totalPages;
}
else
{
startPageIndex = (PageIndex > 5) ? PageIndex - 5 : startPageIndex;
int result = (startPageIndex + 9) - totalPages;
if (result > 0)
{
endPageIndex = totalPages;
startPageIndex -= result;
}
else
{
endPageIndex = startPageIndex + 9;
}
}
BindPageNum(startPageIndex, endPageIndex);
}
private void BindPageNum(int startPageIndex, int endPageIndex)
{
int[] pages = new int[endPageIndex - startPageIndex + 1];
int index = 0;
for (int i = startPageIndex; i <= endPageIndex; i++)
{
pages[index] = i;
index++;
}
rptPageNumber.DataSource = pages;
rptPageNumber.DataBind();
}
private void BindPagingHelperControl()
{
int totalPages = (TotalItemCount % PageSize) == 0 ? TotalItemCount / PageSize : TotalItemCount / PageSize + 1;
//顯示
lbTotalPages.Text = totalPages.ToString();
BindPageNum(totalPages);
//使能
lbtnFirstPage.Enabled = PageIndex > 1;
lbtnPrevPage.Enabled = PageIndex > 1;
lbtnLastPage.Enabled = PageIndex < totalPages;
lbtnNextPage.Enabled = PageIndex < totalPages;
//命令
lbtnFirstPage.CommandArgument = "1";
lbtnPrevPage.CommandArgument = (PageIndex - 1).ToString();
lbtnNextPage.CommandArgument = (PageIndex + 1).ToString();
lbtnLastPage.CommandArgument = totalPages.ToString();
}
private void ReBindData(int pageIndex)
{
PageIndex = pageIndex;
OnPageIndexChanged(new EventArgs());
BindPagingHelperControl();
}
#endregion
#region 事件
public delegate void PageIndexChangedEventHandler(object sender, EventArgs e);
public event PageIndexChangedEventHandler PageIndexChanged;
protected virtual void OnPageIndexChanged(EventArgs e)
{
PageIndexChangedEventHandler handler = PageIndexChanged;
if (handler != null)
{
handler(this, e);
}
}
#endregion
}
}