asp.net repeater and GridView support for DataPager pagination _ Practical Tips

Source: Internet
Author: User
The way to do this is to write a control yourself that inherits the GridView or repeater and implements the IPageableItemContainer interface. The following to be sent by a foreign expert to write the code, the test is effective. When used specifically, to build a class library project, the code compiled into a DLL, you can add to the VS Toolbox!
First, custom repeater
Copy Code code as follows:

Using System.Web.UI;
Using System.Web.UI.WebControls;
Namespace WYJ. Web.Controls
{
<summary>
Repeater with support for DataPager
</summary>
[ToolBoxData ("<{0}:D atapagerrepeater runat=server persistentdatasource=true></{0}:D atapagerrepeater> ")]
public class Datapagerrepeater:repeater, System.Web.UI.WebControls.IPageableItemContainer, INamingContainer
{
<summary>
Number of rows to show
</summary>
public int Maximumrows {get {viewstate["maximumrows"]!= null? (int) viewstate["Maximumrows"]:-1; } }
<summary>
The I-row to show
</summary>
public int startRowIndex {get {viewstate["startrowindex"]!= null? (int) viewstate["startRowIndex"]:-1; } }
<summary>
Total rows. When Pagingindatasource are set to true you must get the total records from the DataSource (without paging) at the fetching Data Event
When Pagingindatasource are set to true and you also need to set this then you load the data the
</summary>
public int Totalrows {get {viewstate["totalrows"]!= null? (int) viewstate["Totalrows"]:-1; set {viewstate["totalrows"] = value;}}
<summary>
If repeater should store data source in view state. If false you are need to get and bind data at post. When using a connected the data source of the. 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 are 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 rebind the Fetchingdata event.
The If is true to 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 are 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;
}
}

What to do with the ASPX page (take the message board of my Site for example):
The first thing to do is register the tags in.
Copy Code code as follows:
<%@ Register assembly= "WYJ. Web.Controls "Namespace=" WYJ. Web.Controls "tagprefix=" WYJ "%>

And then add our repeater.
Copy Code code as follows:

<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" >
&LT;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><div class= "Lvwordcontent" >
<%# ((GeekStudio.ORM.Model.Leaveword) Container.DataItem). Content%>
</div>
</div>
</div>
</ItemTemplate>
</WYJ:DataPagerRepeater>

Added after. NET DataPager, and customize some pagination styles
Copy Code code as follows:

<div class= "Pager" >
<div class= "FR" >
Total <%=math.ceiling ((double) datapager1.totalrowcount/datapager1.pagesize)%> page, <%=datapager1.totalrowcount %> records, per page display
<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= "Home"/>
<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= "Last"/>
</Fields>
</asp:DataPager>
</div>

Background code:
The paging section does not require code. The following code is to toggle the number of displays per page:
Copy Code code as follows:

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 = "";
}

Ii. Custom GridView
Copy Code code as follows:

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 "CreateChildControls" 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 this were created, otherwise cast the datasource to a 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);
}
}
}
}

The usage is similar with repeater, not more hair ~
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.