ASP.NET分页
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; namespace PagerControls { [DefaultProperty("Text")] [ToolboxData("<{0}:PagerControl runat=server></{0}:PagerControl>")] public class PagerControl : WebControl { private int currentPage; // 当前页的页码 private int pageCount; // 总页数 private int recordCount; //总记录数 private bool showPrevious = false; // 是否显示 上一页、第一页 的链接 private bool showNext = false; // 是否显示 下一页、最末页 的链接 private int startPage; // 显示的第一页 的 页码 private int endPage; // 显示的最末页 的 页码 public int pageSize; //分页条数 public PagerControl() { // 当前页之前可以显示的最多链接数,大于此条链接将被隐藏 ViewState["PreviousPageCount"] = 5; // 当前页之后可以显示的最多链接数,大于此条链接将被隐藏 ViewState["AfterPageCount"] = 4; // 供客户端设置样式 ViewState["CssClass"] = "Pager"; } public new string CssClass { get { return ViewState["CssClass"].ToString(); } set { ViewState["CssClass"] = value; } } public int PreviousPageCount { get { return (int)ViewState["PreviousPageCount"]; } set { ViewState["PreviousPageCount"] = value; } } public int AfterPageCount { get { return (int)ViewState["AfterPageCount"]; } set { ViewState["AfterPageCount"] = value; } } public UrlManager UrlManager { get { return (UrlManager)ViewState["UrlManager"]; } set { ViewState["UrlManager"] = value; } } // 添加“第一页”,“上一页”的连接 private void AddPreviousLink(UrlManager UrlManager, HtmlTextWriter output) { output.RenderBeginTag(HtmlTextWriterTag.Li); //output.AddAttribute(HtmlTextWriterAttribute.Class, "PagerIcon"); output.AddAttribute(HtmlTextWriterAttribute.Title, "第一页"); //output.AddAttribute(HtmlTextWriterAttribute.Href, UrlManager.GetPageUrl(1)); output.AddAttribute(HtmlTextWriterAttribute.Onclick, "$(\"#page-content\").load('" + UrlManager.GetPageUrl(1) + "')"); output.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0);"); output.RenderBeginTag(HtmlTextWriterTag.A); output.Write("<<"); output.RenderEndTag(); //output.AddAttribute(HtmlTextWriterAttribute.Class, "PagerIcon"); output.AddAttribute(HtmlTextWriterAttribute.Title, "上一页"); //output.AddAttribute(HtmlTextWriterAttribute.Href, UrlManager.GetPageUrl(currentPage - 1)); output.AddAttribute(HtmlTextWriterAttribute.Onclick, "$(\"#page-content\").load('" + UrlManager.GetPageUrl(currentPage - 1) + "')"); output.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0);"); output.RenderBeginTag(HtmlTextWriterTag.A); output.Write("<"); output.RenderEndTag(); //A output.RenderEndTag(); //Li showPrevious = false; // 只显示一次 } // 添加 “下一页”、“最末页” 的链接 private void AddNextLink(UrlManager UrlManager, HtmlTextWriter output) { output.RenderBeginTag(HtmlTextWriterTag.Li); //output.AddAttribute(HtmlTextWriterAttribute.Class, "pagination page"); output.AddAttribute(HtmlTextWriterAttribute.Title, "下一页"); //output.AddAttribute(HtmlTextWriterAttribute.Href, UrlManager.GetPageUrl(currentPage + 1)); output.AddAttribute(HtmlTextWriterAttribute.Onclick, "$(\"#page-content\").load('" + UrlManager.GetPageUrl(currentPage + 1) + "')"); output.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0);"); output.RenderBeginTag(HtmlTextWriterTag.A); output.Write(">"); output.RenderEndTag(); //output.AddAttribute(HtmlTextWriterAttribute.Class, "pagination page"); output.AddAttribute(HtmlTextWriterAttribute.Title, "最末页"); //output.AddAttribute(HtmlTextWriterAttribute.Href, UrlManager.GetPageUrl(pageCount)); output.AddAttribute(HtmlTextWriterAttribute.Onclick, "$(\"#page-content\").load('" + UrlManager.GetPageUrl(pageCount) + "')"); output.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0);"); output.RenderBeginTag(HtmlTextWriterTag.A); output.Write(">>"); output.RenderEndTag(); output.RenderEndTag(); //Li showNext = false; // 可有可无,程序会跳出循环 } // 根据当前页,当前页之前可以显示的页数,算得从第几页开始进行显示 private void SetStartPage() { // 如果当前页小于它前面所可以显示的条目数, // 那么显示第一页就是实际的第一页 if (currentPage <= PreviousPageCount) { startPage = 1; } else // 这种情况下 currentPage 前面总是能显示完, // 要根据后面的长短确定是不是前面应该多显示 { if (currentPage > PreviousPageCount + 1) showPrevious = true; int linkLength = (pageCount - currentPage + 1) + PreviousPageCount; int startPage = currentPage - PreviousPageCount; while (linkLength < PreviousPageCount + AfterPageCount + 1 && startPage > 1) { linkLength++; startPage--; } this.startPage = startPage; } } // 根据CurrentPage、总页数、当前页之后长度 算得显示的最末页是 第几页 private void SetEndPage() { // 如果当前页加上它之后可以显示的页数 大于 总页数, // 那么显示的最末页就是实际的最末页 if (currentPage + AfterPageCount >= pageCount) { endPage = pageCount; } else { // 这种情况下 currentPage后面的总是可以显示完, // 要根据前面的长短确定是不是后面应该多显示 int linkLength = (currentPage - startPage + 1) + AfterPageCount; int endPage = currentPage + AfterPageCount; while (linkLength < PreviousPageCount + AfterPageCount + 1 && endPage < pageCount) { linkLength++; endPage++; } if (endPage < pageCount) showNext = true; this.endPage = endPage; } } // 显示在页面上 protected override void Render(HtmlTextWriter output) { //////output.AddAttribute(HtmlTextWriterAttribute.Class, CssClass); //////output.RenderBeginTag(HtmlTextWriterTag.Div); if (UrlManager == null) throw new ArgumentNullException("UrlManager 不能为 Null"); // 获取当前页 currentPage = UrlManager.CurrentPageIndex; // 获取总页数 pageCount = UrlManager.PageCount; // 获取总记录数 recordCount = UrlManager.RecordCount; SetStartPage(); SetEndPage(); output.RenderBeginTag(HtmlTextWriterTag.Span); string str = "记录共" + pageCount + "页," + recordCount + "条记录,当前" + currentPage + "页,每页" + pageSize + "条。"; output.Write(String.Format("<span class=\"count\">{0}</span>", str)); //output.Write(String.Format(" ( 第<b>{0}</b>页/共<b>{1}</b>页 )", currentPage, pageCount)); output.RenderEndTag(); // Span output.AddAttribute(HtmlTextWriterAttribute.Class, "pagination page"); output.RenderBeginTag(HtmlTextWriterTag.Ul); if (recordCount > 1) { showPrevious = true; } if (currentPage <= endPage) { showNext = true; } // 循环打印链接 for (int i = startPage; i <= endPage; i++) { if (showPrevious) // 如果需要显示前一页、第一页链接 AddPreviousLink(UrlManager, output); if (i == currentPage) { output.AddAttribute(HtmlTextWriterAttribute.Class, "on"); } output.RenderBeginTag(HtmlTextWriterTag.Li); //output.AddAttribute(HtmlTextWriterAttribute.Href, UrlManager.GetPageUrl(i)); string url = UrlManager.GetPageUrl(i); output.AddAttribute(HtmlTextWriterAttribute.Onclick, "$(\"#page-content\").load('" + url + "')"); output.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0);"); output.RenderBeginTag(HtmlTextWriterTag.A); output.Write(i); output.RenderEndTag(); // A output.RenderEndTag(); // Li if (i == endPage && showNext) // 如果需要显示 下一页、最末页 链接 AddNextLink(UrlManager, output); } output.RenderEndTag(); //Ul ////////output.RenderEndTag(); // Div } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; namespace PagerControls { [Serializable] public abstract class UrlManager { protected int currentPageIndex; // 当前页码 protected int recordCount; // 记录总数 protected int pageSize; // 分页大小 protected int pageCount; // 总页数 protected string queryParam; // 传递页数的参数名称 protected UrlManager(int recordCount, int pageSize, string queryParam) { if (recordCount < 0) throw new ArgumentOutOfRangeException("recordCount 应该大于等于 0 !"); if (pageSize <= 0) throw new ArgumentOutOfRangeException("pageSize 应该大于 0 !"); if (String.IsNullOrEmpty(queryParam)) throw new ArgumentNullException("queryParam 不能为空!"); // 设置私有变量 this.recordCount = recordCount; this.pageSize = pageSize; this.queryParam = queryParam; this.pageCount = getPageCount(recordCount, pageSize); this.currentPageIndex = getPageIndex(recordCount, pageCount, queryParam); } // 获取页码总数 private int getPageCount(int recordCount, int pageSize) { int pageCount; // 如果记录数为0,也认为有一页(因为至少需要进行一个显示) if (recordCount == 0) { pageCount = 1; } else { // 计算总页数 if (recordCount % pageSize == 0) pageCount = recordCount / pageSize; else pageCount = (recordCount / pageSize) + 1; } return pageCount; } // 从Url参数中获得但前页码 private int getPageIndex(int recordCount, int pageCount, string queryParam) { if (recordCount == 0) return 1; // 如果记录数为0,则显示为第一页 int pageIndex; // 从Url参数获得当前页码 string queryIndex = HttpContext.Current.Request.QueryString[queryParam]; // 对页码进行一些校验 if (string.IsNullOrEmpty(queryIndex)) pageIndex = 1; // 显示第一页 else { try { pageIndex = Math.Abs(int.Parse(queryIndex)); if (pageIndex == 0) pageIndex = 1; // 如果当前页大于总页数,设当前页为最后一页 if (pageIndex > pageCount) pageIndex = pageCount; } catch { pageIndex = 1; // 显示第一页 } } return pageIndex; } public int PageCount { get { return pageCount; } } public int RecordCount { get { return recordCount; } } public int PageSize { get { return pageSize; } } public int CurrentPageIndex { get { return currentPageIndex; } } public abstract string GetPageUrl(int pageIndex); } // 我提供的默认 DefaultUrlManager,如果你要使用控件,只要继承自UrlManager // 并覆盖 GetPageUrl() 方法即可。 [Serializable] public class DefaultUrlManager : UrlManager { public DefaultUrlManager(int recordCount, int pageSize, string queryParam) : base(recordCount, pageSize, queryParam) { } public DefaultUrlManager(int recordCount, int pageSize) : this(recordCount, pageSize, "Page") { } public DefaultUrlManager(int recordCount) : this(recordCount, 10) { } // 获得页面Url public override string GetPageUrl(int pageIndex) { string pageUrl = HttpContext.Current.Request.RawUrl; string pattern = @"(?<=[?&]" + queryParam + @"=)(\d+)\b"; Regex reg = new Regex(pattern, RegexOptions.IgnoreCase); // 如果找到匹配,也就是URL中含有类似 ?page=3 或者 &page=4 这样的字符串 // 则对后面的数值进行替换 if (reg.IsMatch(pageUrl)) { pageUrl = reg.Replace(pageUrl, pageIndex.ToString()); } else { string queryString = HttpContext.Current.Request.Url.Query; if (string.IsNullOrEmpty(queryString)) pageUrl += "?" + queryParam + "=" + pageIndex.ToString(); else pageUrl += "&" + queryParam + "=" + pageIndex.ToString(); } return pageUrl; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PagerControls { // 通过 manager 提供的参数算得 GetRange()类 需要的参数(起始索引index,以及长度count): // 然后调用 List<T> 的 GetRange()方法。 public class PagerAdapter<T> { List<T> list; public PagerAdapter(List<T> list) { this.list = list; } /// <summary> /// 数据加载完毕后,从 List 集合中取得分页信息 /// </summary> /// <param name="manager"></param> /// <returns></returns> public List<T> GetRange(UrlManager manager) { int currentPageIndex = manager.CurrentPageIndex; int pageSize = manager.PageSize; int recordCount = manager.RecordCount; int count, start; if (currentPageIndex * pageSize > recordCount) { count = pageSize - (currentPageIndex * pageSize - recordCount); } else { count = pageSize; } start = (currentPageIndex - 1) * pageSize; return list.GetRange(start, count); } public PagerAdapter() { } /// <summary> /// 获取分页信息,自定义扩展方法 SQL 数据库分页方式,取得当前页码 /// </summary> /// <param name="manager"></param> /// <param name="_pageIndex"></param> /// <param name="_pageSize"></param> public void GetPage(UrlManager manager, ref int _pageIndex, ref int _pageSize) { int currentPageIndex = manager.CurrentPageIndex; int pageSize = manager.PageSize; int recordCount = manager.RecordCount; if (currentPageIndex <= 0) { _pageIndex = 1; } else { _pageIndex = currentPageIndex; } _pageSize = pageSize; } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; namespace PagerControls.Test { public class PagerInfo { public static string RequestRowNum(string from, string where) { try { string bsSQL = "SELECT COUNT(*) RowNum from " + from + where; return ""; } catch (Exception ex) { throw ex; } } public static DataTable RequestPage(string from, string where, string field, string pageSize, string pageIndex) { try { string bsSQL = "declare @pagesize integer,@cpage integer; "; bsSQL += "set @pagesize ="+pageSize+";"; bsSQL += "set @cpage = "+pageIndex+";"; bsSQL += "select top (@pagesize) * from " + from + " where " + where + " AND " + field + " not in(select top ((@cpage - 1) * @pagesize) " + field + " from " + from + " where " + where + " order by " + field + " desc) order by " + field + " desc"; return null; } catch (Exception ex) { throw ex; } } } }
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PagerControls.Test.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div class="mange-company-tab"> <div class="tab-main"> <table class="table table-hover table-striped"> <thead> <tr> <th>姓名</th> <th>账户 </th> <th>联系电话</th> <th>操作</th> </tr> </thead> <tbody> <asp:Literal ID="literRecord" runat="server"></asp:Literal> </tbody> </table> </div> <div class="tab-bottom"> <asp:PlaceHolder ID="phHolder" runat="server"></asp:PlaceHolder> </div> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace PagerControls.Test { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //RequestUsers(); this.RequestData(); } } /// <summary> /// 数据库分页取数据 /// </summary> private void RequestData() { try { string num = PagerInfo.RequestRowNum("Users", " where Status = 1 "); // 动态使用方式 PagerControl pager = new PagerControl(); pager.pageSize = 10; // 设置根据Request.QueryString获取页码的参数 DefaultUrlManager manager = new DefaultUrlManager(Convert.ToInt32(num), pager.pageSize, "P"); pager.UrlManager = manager; // 因为 HttpContext 的原因 UrlManager 不可串行化 // 如果你实现了自己的IUrlManager接口,这里可能是这样: // pager.UrlManager = new YourUrlManger(133); //pager.CssClass = "GreenStyle"; // 设置颜色 pager.PreviousPageCount = 3; // 设置当前页之前显示的最大链接数 pager.AfterPageCount = 3; // 设置当前也之后可以显示的最大链接数 // 将控件加入到页面上 phHolder.Controls.Add(pager); // 使用 GetRange() 方法进行分页 PagerAdapter<object> adpter = new PagerAdapter<object>(); int pageIndex = 1; int pageSize = 10; adpter.GetPage(manager, ref pageIndex, ref pageSize); DataTable dt = PagerInfo.RequestPage("Users", " Status = 1 ", "ID",pageSize.ToString(), pageIndex.ToString()); StringBuilder strHtml = new StringBuilder(); for (int i = 0; i < dt.Rows.Count; i++) { strHtml.Append("<tr><td>" + dt.Rows[i]["NickName"].ToString() + "</td><td>" + dt.Rows[i]["UserName"].ToString() + "</td><td>" + dt.Rows[i]["Mobile"].ToString() + "</td><td uid=" + dt.Rows[i]["ID"].ToString() + " cid=" + dt.Rows[i]["CompanyID"].ToString() + "><a href=\"javascript:void(0);\" class=\"edit-user\"><i class=\"icon icon-edit\"></i></a><a href=\"javascript:void(0);\" class=\"del-user\"><i class=\"icon icon-del\"></i></a></td></tr>"); } this.literRecord.Text = strHtml.ToString(); } catch (Exception) { throw; } } } }