asp.net中讓Repeater和GridView支持DataPager分頁(yè)
一、自定義Repeater
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WYJ.Web.Controls
{
/// <summary>
/// Repeater with support for DataPager
/// </summary>
[ToolboxData("<{0}:DataPagerRepeater runat=server PersistentDataSource=true></{0}:DataPagerRepeater>")]
public class DataPagerRepeater : Repeater, System.Web.UI.WebControls.IPageableItemContainer, INamingContainer
{
/// <summary>
/// Number of rows to show
/// </summary>
public int MaximumRows { get { return ViewState["MaximumRows"] != null ? (int)ViewState["MaximumRows"] : -1; } }
/// <summary>
/// First row to show
/// </summary>
public int StartRowIndex { get { return ViewState["StartRowIndex"] != null ? (int)ViewState["StartRowIndex"] : -1; } }
/// <summary>
/// Total rows. When PagingInDataSource is set to true you must get the total records from the datasource (without paging) at the FetchingData event
/// When PagingInDataSource is set to true you also need to set this when you load the data the first time.
/// </summary>
public int TotalRows { get { return ViewState["TotalRows"] != null ? (int)ViewState["TotalRows"] : -1; } set { ViewState["TotalRows"] = value; } }
/// <summary>
/// If repeater should store data source in view state. If false you need to get and bind data at post back. When using a connected data source this is handled by the data source.
/// </summary>
public bool PersistentDataSource
{
get { return ViewState["PersistentDataSource"] != null ? (bool)ViewState["PersistentDataSource"] : true; }
set { ViewState["PersistentDataSource"] = value; }
}
/// <summary>
/// Set to true if you want to handle paging in the data source.
/// Ex if you are selecting data from the database and only select the current rows
/// you must set this property to true and get and rebind data at the FetchingData event.
/// If this is true you must also set the TotalRecords property at the FetchingData event.
/// </summary>
/// <seealso cref="FetchingData"/>
/// <seealso cref="TotalRows"/>
public bool PagingInDataSource
{
get { return ViewState["PageingInDataSource"] != null ? (bool)ViewState["PageingInDataSource"] : false; }
set { ViewState["PageingInDataSource"] = value; }
}
/// <summary>
/// Checks if you need to rebind data source at postback
/// </summary>
public bool NeedsDataSource
{
get
{
if (PagingInDataSource)
return true;
if (IsBoundUsingDataSourceID == false && !Page.IsPostBack)
return true;
if (IsBoundUsingDataSourceID == false && PersistentDataSource == false && Page.IsPostBack)
return true;
else
return false;
}
}
/// <summary>
/// Loading ViewState
/// </summary>
/// <param name="savedState"></param>
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
//if (Page.IsPostBack)
//{
// if (!IsBoundUsingDataSourceID && PersistentDataSource && ViewState["DataSource"] != null)
// {
// this.DataSource = ViewState["DataSource"];
// this.DataBind(true);
// }
// if (IsBoundUsingDataSourceID)
// {
// this.DataBind();
// }
//}
}
protected override void OnLoad(System.EventArgs e)
{
if (Page.IsPostBack)
{
if (NeedsDataSource && FetchingData != null)
{
if (PagingInDataSource)
{
SetPageProperties(StartRowIndex, MaximumRows, true);
}
FetchingData(this, null);
}
if (!IsBoundUsingDataSourceID && PersistentDataSource && ViewState["DataSource"] != null)
{
this.DataSource = ViewState["DataSource"];
this.DataBind();
}
if (IsBoundUsingDataSourceID)
{
this.DataBind();
}
}
base.OnLoad(e);
}
/// <summary>
/// Method used by pager to set totalrecords
/// </summary>
/// <param name="startRowIndex">startRowIndex</param>
/// <param name="maximumRows">maximumRows</param>
/// <param name="databind">databind</param>
public void SetPageProperties(int startRowIndex, int maximumRows, bool databind)
{
ViewState["StartRowIndex"] = startRowIndex;
ViewState["MaximumRows"] = maximumRows;
if (TotalRows > -1)
{
if (TotalRowCountAvailable != null)
{
TotalRowCountAvailable(this, new PageEventArgs((int)ViewState["StartRowIndex"], (int)ViewState["MaximumRows"], TotalRows));
}
}
}
/// <summary>
/// OnDataPropertyChanged
/// </summary>
protected override void OnDataPropertyChanged()
{
if (MaximumRows != -1 || IsBoundUsingDataSourceID)
{
this.RequiresDataBinding = true;
}
base.OnDataPropertyChanged();
}
/// <summary>
/// Renders only current items selected by pager
/// </summary>
/// <param name="writer"></param>
protected override void RenderChildren(HtmlTextWriter writer)
{
if (!PagingInDataSource && MaximumRows != -1)
{
foreach (RepeaterItem item in this.Items)
{
if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
{
item.Visible = false;
if (item.ItemIndex >= (int)ViewState["StartRowIndex"] && item.ItemIndex < ((int)ViewState["StartRowIndex"] + (int)ViewState["MaximumRows"]))
{
item.Visible = true;
}
}
else
{
item.Visible = true;
}
}
}
base.RenderChildren(writer);
}
/// <summary>
/// Get Data
/// </summary>
/// <returns></returns>
protected override System.Collections.IEnumerable GetData()
{
System.Collections.IEnumerable dataObjects = base.GetData();
if (dataObjects == null && this.DataSource != null)
{
if (this.DataSource is System.Collections.IEnumerable)
dataObjects = (System.Collections.IEnumerable)this.DataSource;
else
dataObjects = ((System.ComponentModel.IListSource)this.DataSource).GetList();
}
if (!PagingInDataSource && MaximumRows != -1 && dataObjects != null)
{
int i = -1;
if (dataObjects != null)
{
i = 0;
foreach (object o in dataObjects)
{
i++;
}
}
ViewState["TotalRows"] = i;
if (!IsBoundUsingDataSourceID && PersistentDataSource)
ViewState["DataSource"] = this.DataSource;
SetPageProperties(StartRowIndex, MaximumRows, true);
}
if (PagingInDataSource && !Page.IsPostBack)
{
SetPageProperties(StartRowIndex, MaximumRows, true);
}
return dataObjects;
}
/// <summary>
/// Event when pager/repeater have counted total rows
/// </summary>
public event System.EventHandler<PageEventArgs> TotalRowCountAvailable;
/// <summary>
/// Event when repeater gets the data on postback
/// </summary>
public event System.EventHandler<PageEventArgs> FetchingData;
}
}
ASPX頁(yè)面要做的事情(以我網(wǎng)站的留言板為例):
首先得把標(biāo)簽注冊(cè)進(jìn)來(lái)
然后添加我們的Repeater
<WYJ:DataPagerRepeater ID="rptLeaveword" runat="server" PersistentDataSource="true">
<ItemTemplate>
<div class="leavewordentry">
<div class="datebox">
<div class="time">
<%# ((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Posttime.ToString("HH:mm") %></div>
<div class="day">
<%# ((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Posttime.ToString("dd") %>
</div>
<div class="month">
<%# ((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Posttime.ToString("MMM", new CultureInfo("en-US")).ToUpper() %><%# ((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Posttime.ToString(" yyyy") %></div>
</div>
<div class="contentbox">
<h2 class="username">
<a id="<%# GeekStudio.Common.IdEncryptor.EncodeId(((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Id) %>"
name="<%# GeekStudio.Common.IdEncryptor.EncodeId(((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Id) %>">
<%# ((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Username %></a></h2>
<div class="lvwordcontent">
<%# ((GeekStudio.ORM.Model.Leaveword)Container.DataItem).Content %>
</div>
</div>
</div>
</ItemTemplate>
</WYJ:DataPagerRepeater>
之后添加.NET自帶的DataPager,并自定義一些分頁(yè)樣式
<div class="pager">
<div class="fr">
共<%=Math.Ceiling((double)DataPager1.TotalRowCount / DataPager1.PageSize)%>頁(yè),<%=DataPager1.TotalRowCount%>條記錄,每頁(yè)顯示
<asp:LinkButton ID="lnkbtn10" CssClass="currentpagesize" runat="server" OnClick="lnkbtn10_Click">10</asp:LinkButton>
<asp:LinkButton ID="lnkbtn20" runat="server" OnClick="lnkbtn20_Click">20</asp:LinkButton>
<asp:LinkButton ID="lnkbtn30" runat="server" OnClick="lnkbtn30_Click">30</asp:LinkButton>
</div>
<asp:DataPager ID="DataPager1" PagedControlID="rptLeaveword" runat="server">
<Fields>
<asp:NextPreviousPagerField ShowFirstPageButton="True" ShowNextPageButton="False"
ShowPreviousPageButton="False" FirstPageText="首頁(yè)" />
<asp:NextPreviousPagerField ShowNextPageButton="False" ButtonType="Image" PreviousPageImageUrl="~/Images/icons/pagerprevious.png" />
<asp:NumericPagerField CurrentPageLabelCssClass="current" />
<asp:NextPreviousPagerField ShowPreviousPageButton="False" ButtonType="Image" NextPageImageUrl="~/Images/icons/pagernext.png" />
<asp:NextPreviousPagerField ShowLastPageButton="True" ShowNextPageButton="False"
ShowPreviousPageButton="False" LastPageText="尾頁(yè)" />
</Fields>
</asp:DataPager>
</div>
后臺(tái)代碼:
分頁(yè)部分不需要代碼。下面發(fā)的代碼是切換每頁(yè)顯示數(shù)量的:
protected void lnkbtn10_Click(object sender, EventArgs e)
{
DataPager1.PageSize = 10;
lnkbtn10.CssClass = "currentpagesize";
lnkbtn20.CssClass = "";
lnkbtn30.CssClass = "";
}
protected void lnkbtn20_Click(object sender, EventArgs e)
{
DataPager1.PageSize = 20;
lnkbtn20.CssClass = "currentpagesize";
lnkbtn10.CssClass = "";
lnkbtn30.CssClass = "";
}
protected void lnkbtn30_Click(object sender, EventArgs e)
{
DataPager1.PageSize = 30;
lnkbtn30.CssClass = "currentpagesize";
lnkbtn10.CssClass = "";
lnkbtn20.CssClass = "";
}
二、自定義GridView
using System;
using System.Collections;
using System.Web.UI.WebControls;
namespace WYJ.Web.Controls
{
/// <summary>
/// DataPagerGridView is a custom control that implements GrieView and IPageableItemContainer
/// </summary>
public class DataPagerGridView : GridView, IPageableItemContainer
{
public DataPagerGridView()
: base()
{
PagerSettings.Visible = false;
}
/// <summary>
/// TotalRowCountAvailable event key
/// </summary>
private static readonly object EventTotalRowCountAvailable = new object();
/// <summary>
/// Call base control's CreateChildControls method and determine the number of rows in the source
/// then fire off the event with the derived data and then we return the original result.
/// </summary>
/// <param name="dataSource"></param>
/// <param name="dataBinding"></param>
/// <returns></returns>
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
int rows = base.CreateChildControls(dataSource, dataBinding);
// if the paging feature is enabled, determine the total number of rows in the datasource
if (this.AllowPaging)
{
// if we are databinding, use the number of rows that were created, otherwise cast the datasource to an Collection and use that as the count
int totalRowCount = dataBinding ? rows : ((ICollection)dataSource).Count;
// raise the row count available event
IPageableItemContainer pageableItemContainer = this as IPageableItemContainer;
this.OnTotalRowCountAvailable(new PageEventArgs(pageableItemContainer.StartRowIndex, pageableItemContainer.MaximumRows, totalRowCount));
// make sure the top and bottom pager rows are not visible
if (this.TopPagerRow != null)
this.TopPagerRow.Visible = false;
if (this.BottomPagerRow != null)
this.BottomPagerRow.Visible = false;
}
return rows;
}
/// <summary>
/// Set the control with appropriate parameters and bind to right chunk of data.
/// </summary>
/// <param name="startRowIndex"></param>
/// <param name="maximumRows"></param>
/// <param name="databind"></param>
void IPageableItemContainer.SetPageProperties(int startRowIndex, int maximumRows, bool databind)
{
int newPageIndex = (startRowIndex / maximumRows);
this.PageSize = maximumRows;
if (this.PageIndex != newPageIndex)
{
bool isCanceled = false;
if (databind)
{
// create the event arguments and raise the event
GridViewPageEventArgs args = new GridViewPageEventArgs(newPageIndex);
this.OnPageIndexChanging(args);
isCanceled = args.Cancel;
newPageIndex = args.NewPageIndex;
}
// if the event wasn't cancelled change the paging values
if (!isCanceled)
{
this.PageIndex = newPageIndex;
if (databind)
this.OnPageIndexChanged(EventArgs.Empty);
}
if (databind)
this.RequiresDataBinding = true;
}
}
/// <summary>
/// IPageableItemContainer's StartRowIndex = PageSize * PageIndex properties
/// </summary>
int IPageableItemContainer.StartRowIndex
{
get { return this.PageSize * this.PageIndex; }
}
/// <summary>
/// IPageableItemContainer's MaximumRows = PageSize property
/// </summary>
int IPageableItemContainer.MaximumRows
{
get { return this.PageSize; }
}
/// <summary>
///
/// </summary>
event EventHandler<PageEventArgs> IPageableItemContainer.TotalRowCountAvailable
{
add { base.Events.AddHandler(DataPagerGridView.EventTotalRowCountAvailable, value); }
remove { base.Events.RemoveHandler(DataPagerGridView.EventTotalRowCountAvailable, value); }
}
/// <summary>
///
/// </summary>
/// <param name="e"></param>
protected virtual void OnTotalRowCountAvailable(PageEventArgs e)
{
EventHandler<PageEventArgs> handler = (EventHandler<PageEventArgs>)base.Events[DataPagerGridView.EventTotalRowCountAvailable];
if (handler != null)
{
handler(this, e);
}
}
}
}
用法與Repeater類(lèi)似,不多發(fā)了~
- 在ASP.NET 2.0中操作數(shù)據(jù)之四十一:DataList和Repeater數(shù)據(jù)分頁(yè)
- .NET實(shí)現(xiàn)Repeater控件+AspNetPager控件分頁(yè)
- asp.net Repeater分頁(yè)實(shí)例(PageDataSource的使用)
- asp.net中使用repeater和PageDataSource搭配實(shí)現(xiàn)分頁(yè)代碼
- asp.net下Repeater使用 AspNetPager分頁(yè)控件
- asp.net Repeater之非常好的數(shù)據(jù)分頁(yè)
- asp.net repeater手寫(xiě)分頁(yè)實(shí)例代碼
- ASP.NET程序中用Repeater實(shí)現(xiàn)分頁(yè)
- .NET中的repeater簡(jiǎn)介及分頁(yè)效果
相關(guān)文章
ASP.NetCore使用Swagger實(shí)戰(zhàn)
這篇文章主要介紹了ASP.NetCore使用Swagger實(shí)戰(zhàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11asp.net內(nèi)置對(duì)象 Response對(duì)象使用介紹
這篇文章主要介紹了asp.net內(nèi)置對(duì)象:Response對(duì)象使用介紹,對(duì)Response對(duì)象感興趣的小伙伴們可以參考一下2015-11-11.net?程序通過(guò)?crontab?無(wú)法啟動(dòng)手動(dòng)執(zhí)行腳本啟動(dòng)的方法
.net 網(wǎng)關(guān)程序需要設(shè)置定時(shí)重啟,按照日常操作先把正在運(yùn)行的 PID kill 掉后,再執(zhí)行啟動(dòng)服務(wù)。通過(guò)腳本無(wú)法啟動(dòng),試著把 .net 程序?qū)懗煞?wù)后,發(fā)現(xiàn)是可以正常重啟的,本文給大家介紹下.net 程序通過(guò) crontab 無(wú)法啟動(dòng)手動(dòng)執(zhí)行腳本啟動(dòng),感興趣的朋友一起看看吧2021-12-12理解ASP.NET Core 依賴(lài)注入(Dependency Injection)
把有依賴(lài)關(guān)系的類(lèi)放到容器中,解析出這些類(lèi)的實(shí)例,就是依賴(lài)注入。目的是實(shí)現(xiàn)類(lèi)的解耦。本文主要介紹了ASP.NET Core 依賴(lài)注入(Dependency Injection),需要了解具體內(nèi)容的可以仔細(xì)閱讀這篇文章,希望對(duì)你有所幫助2021-09-09.Net?Core授權(quán)認(rèn)證方案JWT(JSON?Web?Token)初探
這篇文章介紹了.Net?Core授權(quán)認(rèn)證方案JWT,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-06-06ASP.NET網(wǎng)站導(dǎo)航及導(dǎo)航控件如何使用
這篇文章主要介紹了ASP.NET網(wǎng)站導(dǎo)航及導(dǎo)航控件如何使用,需要的朋友可以參考下2015-09-09ASP.NET Core使用AutoMapper實(shí)現(xiàn)實(shí)體映射
本文詳細(xì)講解了ASP.NET Core使用AutoMapper實(shí)現(xiàn)實(shí)體映射的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-03-03.net開(kāi)發(fā)人員常犯的錯(cuò)誤分析小結(jié)
我最新一直在和新手和入手級(jí)開(kāi)發(fā)人員打交道,我注意到一些開(kāi)發(fā)人員(甚至是老手)在粗心時(shí)常犯的錯(cuò)誤。這些錯(cuò)誤各不相同,從工具的使用到網(wǎng)絡(luò)服務(wù)的適當(dāng)應(yīng)用都有。以下是六個(gè)主要的開(kāi)發(fā)錯(cuò)誤。2009-03-03asp.net實(shí)現(xiàn)圖片以二進(jìn)制流輸出的兩種方法
這篇文章主要介紹了asp.net實(shí)現(xiàn)圖片以二進(jìn)制流輸出的兩種方法,以簡(jiǎn)單實(shí)例形式分析了asp.net實(shí)現(xiàn)以二進(jìn)制流形式讀寫(xiě)圖片文件的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-12-12