ASP.NET分页控件
这个在用户控件一用一次
<%@ Register Assembly="Uni2Uni.ERP.Common" Namespace="Uni2Uni.ERP.Common.PageBar"
TagPrefix="cc1" %>
<cc1:PageBar ID="pageBar" runat="server" Mode="Post" />
然后使用那个用户控件
[html]
<uc1:PageBarControl ID="PageBarControl1" runat="server" />
PageBarControl1.PageBar.Click += new EventHandler(PagerChange);
private void PagerChange(object sender, EventArgs e)
{
var queryEntity = ViewState["queryEntity"] as DamagedQueryEntity;
GetPageData(queryEntity, false);
}
private void GetPageData(DamagedQueryEntity queryEntity, bool bFirst = true)
{
if (bFirst)
PageBarControl1.PageBar.CurrentIndex = 1;
int totalCount;
var list = bll.GetDamagedOrderPage(PageBarControl1.PageBar.CurrentIndex, PageBarControl1.PageBar.Size, out totalCount, queryEntity);
this.PageBarControl1.PageBar.Total = totalCount;
this.bindData.DataSource = list;
this.bindData.DataBind();
}
源码
[html]
using System;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
[assembly: WebResource("Uni2Uni.ERP.Common.PageBar.PageBar.css", "text/css", PerformSubstitution = true)]
namespace Uni2Uni.ERP.Common.PageBar
{
public enum PageBarMode
{
Get,
Post
}
#region - PageBar -
/// <summary>
/// 分页控件
/// </summary>
[ToolboxData("<{0}:PageBar runat=\"server\" />")]
[DefaultEvent("Click")]
[DefaultProperty("Size")]
public sealed class PageBar : WebControl, IPostBackEventHandler
{
#region - Properties -
#region = Total =
/// <summary>
/// 总共有多少记录集合
/// </summary>
/// <value>The total.</value>
[Category("Data"), Description("总共有多少记录集合")]
public int Total
{
get
{
object o = ViewState["Total"];
return o == null ? 0 : (int)o;
}
set { ViewState["Total"] = value; }
}
#endregion
#region = CurrentIndex =
/// <summary>
/// 当前使用的页面
/// </summary>
/// <value>The index of the current.</value>
[Category("Data"), Description("当前使用的页面")]
public int CurrentIndex
{
get
{
object o = ViewState["CurrentIndex"];
int _currentindex = ((o == null) ? 0 : (int)o);
if (_currentindex == 0)
{
_currentindex = 1;
if (string.IsNullOrEmpty(UrlFormatString) == false)
{
string url = Page.Request.Url.ToString();
string urlformat = string.Format(UrlFormatString, @"(\d+)");
urlformat = urlformat.Replace("?", "\\?");
urlformat = Regex.Replace(urlformat, "#.+$", string.Empty);
Match m = Regex.Match(url, urlformat, RegexOptions.IgnoreCase);
if (m.Success)
{
string value = m.Groups[1].Value;
if (string.IsNullOrEmpty(value) == false)
{
_currentindex = int.Parse(value);
}
}
}
else
{
if (Page.Request.QueryString[QueryStringKey] != null)
{
int.TryParse(Page.Request.QueryString[QueryStringKey], out _currentindex);
}
}
}
return _currentindex;
}
set { ViewState["CurrentIndex"] = value; }
}
#endregion
#region = Size =
/// <summary>
/// 每个页面显示多少记录集合
/// </summary>
/// <value>The size.</value>
[Category("Data"), Description("每个页面显示多少记录集合")]
public int Size
{
get
{
object o = ViewState["Size"];
return o == null ? 10 : (int)o;
}
set { ViewState["Size"] = value; }
}
#endregion
#region = Displaysize =
/// <summary>
/// 显示页脚,控件显示多少页面数
/// </summary>
/// <value>The displaysize.</value>
[Category("Data"), Description("控件显示多少页面数")]
public int Displaysize
{
get
{
object o = ViewState["Displaysize"];
return o == null ? 10 : (int)o;
}
set { ViewState["Displaysize"] = value; }
}
#endregion
#region = Unit =
/// <summary>
/// 记录的单位
/// </summary>
/// <value>The unit.</value>
[Category("Appearance"), Description("记录的单位")]
public string Unit
{
get
{
object o = ViewState["Unit"];
return o == null ? string.Empty : (string)o;
}
set { ViewState["Unit"] = value; }
}
#endregion
#region = UrlFormatString =
[
Category("Property"),
Description("获取或设置 URL 显示格式。"),
DefaultValue("")
]
public string UrlFormatString
{
get
{
object o = ViewState["UrlFormatString"];
return o == null ? string.Empty : (string)o;
}
set { ViewState["UrlFormatString"] = value; }
}
#endregion
#region = QueryStringKey =
/// <summary>
/// 传递值是使用的关键字
/// </summary>
/// <value>The query string key.</value>
[Description("传递值是使用的关键字"), DefaultValue("page")]
public string QueryStringKey
{
get
{
object o = ViewState["QueryStringKey"];
return o == null ? "page" : (string)o;
}
set { ViewState["QueryStringKey"] = value; }
}
#endregion
#region = 跳转的页数 =
/// <summary>
/// 跳转的页数
/// </summary>
[Browsable(true)]
[Bindable(true, BindingDirection.TwoWay)]
[DefaultValue("")]
[Localizable(true)]
[PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty)]
[Description("跳转的页数")]
public string Text
{
get
{
return ViewState["Text"] == null ? "" : ViewState["Text"].ToString();
}
set
{
ViewState["Text"] = value;
}
}
#endregion
#region = Format =
/// <summary>
/// 数字格式化
/// </summary>
/// <value>The format.</value>
[Description("数字格式化"), DefaultValue("")]
public string Format
{
get
{
object o = ViewState["Format"];
return o == null ? string.Empty : (string)o;
}
set { ViewState["Format"] = value; }
}
#endregion
#region = NextPageImageUrl =
/// <summary>
/// 下一页图片路径
/// </summary>
/// <value>The next page image URL.</value>
[Description("下一页图片路径"), DefaultValue("")]
public string NextPageImageUrl
{
get
{
object o = ViewState["NextPageImageUrl"];
return o == null ? string.Empty : (string)o;
}
set { ViewState["NextPageImageUrl"] = value; }
}
#endregion
#region = LastPageImageUrl =
private string _lastimage = string.Empty;
/// <summary>
/// 上一页图片路径
/// </summary>
/// <value>The last page image URL.</value>
[Description("上一页图片路径"), DefaultValue("")]
public string LastPageImageUrl
{
get
{
object o = ViewState["LastPageImageUrl"];
return o == null ? string.Empty : (string)o;
}
set { ViewState["LastPageImageUrl"] = value; }
}
#endregion
#region = Mode =
[
Category("Property"),
Description("Pagebar的模式"),
DefaultValue("")
]
public PageBarMode Mode
{
get
{
object o = ViewState["Mode"];
return o == null ? PageBarMode.Get : (PageBarMode)o;
}
set { ViewState["Mode"] = value; }
}
#endregion
#region = ValidationGroup =
[Category("Behavior"), DefaultValue(""), Themeable(false), Description("PostBackControl_ValidationGroup")]
public string ValidationGroup
{
get
{
var text1 = (string)ViewState["ValidationGroup"];
if (text1 != null)
{
return text1;
}
return string.Empty;
}
set { ViewState["ValidationGroup"] = value; }
}
#endregion
#region = CausesValidation =
/// <summary>
/// 获取或设置一个值,该值指示在单击 LinkButton 控件时是否执行验证。
/// </summary>
/// <value><c>true</c> if [causes validation]; otherwise, <c>false</c>.</value>
[Category("Behavior"), Themeable(false), Description("Button_CausesValidation"), DefaultValue(true)]
public bool CausesValidation
{
get
{
object obj1 = ViewState["CausesValidation"];
if (obj1 != null)
{
return (bool)obj1;
}
return true;
}
set { ViewState["CausesValidation"] = value; }
}
#endregion
#region = Target =
/// <summary>
/// Gets or sets the target.
/// </summary>
/// <value>The target.</value>
[
Category("Navigation"),
TypeConverter(typeof(TargetConverter)),
DefaultValue(""),
Description("HyperLink_Target")]
public string Target
{
get
{
var text1 = (string)ViewState["Target"];
if (text1 != null)
{
return text1;
}
return "_self";
}
set { ViewState["Target"] = value; }
}
#endregion
#endregion
#region - Event -
#region = OnClick =
private static readonly object EventClick = new object();
[Description("PageBar_OnClick"), Category("Action")]
public event EventHandler Click
{
add { Events.AddHandler(EventClick, value); }
remove { Events.RemoveHandler(EventClick, value); }
}
#endregion
#endregion
#region = OnPreRender =
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.PreRender"></see> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs"></see> object that contains the event data.</param>
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
string cssKey = "PageBarCss";
if (Page == null || Page.Header == null)
{
return;
}
if (string.IsNullOrEmpty(CssClass))
{
CssClass = "PageBar";
}
if (Page.Header.FindControl(cssKey) == null && CssClass == "PageBar")
{
string css = Page.ClientScript.GetWebResourceUrl(GetType(), "Uni2Uni.ERP.Common.PageBar.PageBar.css");
var hl = new HtmlLink();
hl.ID = cssKey;
hl.Href = css;
hl.Attributes["type"] = "text/css";
hl.Attributes["rel"] = "stylesheet";
//this.Page.Header.Controls.Add(hl);
CssClass = "PageBar";
}
}
#endregion
#region = RenderContents =
/// <summary>
/// Renders the contents of the control to the specified writer. This method is used primarily by control developers.
/// </summary>
/// <param name="writer">A <see cref="T:System.Web.UI.HtmlTextWriter"></see> that represents the output stream to render HTML content on the client.</param>
protected override void RenderContents(HtmlTextWriter writer)
{
base.RenderContents(writer);
#region - Valid -
if (IsEnabled == false)
{
return;
}
if (Size == 0 || Displaysize == 0)
{
return;
}
#endregion
if (Total > 0 && CurrentIndex > 0)
{
double dPageCount = 1.0 * Total / Size;
int PageCount = Convert.ToInt32(Math.Ceiling(dPageCount)); //共多少页
PostBackOptions options = GetPostBackOptions("{0}");
string srt = Page.ClientScript.GetPostBackEventReference(options, true);
//---【新添加】
//只能输入正整数
string js = "<script type=\"text/javascript\">var postbackstring=\"" + srt + "\";var total=" + PageCount + "; function PositiveInteger(element, keyCode) {if (keyCode == 9 || keyCode == 116 || (keyCode >= 35 && keyCode <= 40)) {return true;}if ($(element).val().length == 0 && (keyCode == 96 || keyCode==48)){return false;}return (keyCode >= 96 && keyCode <= 105 || keyCode == 8 || (keyCode >= 48 && keyCode <= 57));}function validatePage(element){if($(\"#goPage\").val()==\"\"){alert(\"请输入跳转页数。\");return false;}if($(\"#goPage\").val()>total){alert(\"跳转页数不能大于总页数。\");return false;}$(element).attr(\"href\",postbackstring.replace(\"{0}\",$(\"#goPage\").val()));return true;}</script>";
writer.Write(js);
if (CurrentIndex > PageCount)
{
CurrentIndex = PageCount;
}
//总共2784主题
writer.Write(PageBarResource.Total);
//writer.Write("总共");
writer.Write(" ");
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write(Total.ToString(Format));
writer.RenderEndTag();
writer.Write(Unit);
writer.Write(", ");
writer.Write(PageBarResource.Page);
//writer.Write("当前");
writer.Write(" ");
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write(CurrentIndex.ToString(Format));
writer.RenderEndTag();
writer.Write("/");
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write(PageCount.ToString(Format));
writer.RenderEndTag();
if (PageCount > 1)
{
writer.Write(",");
int PagerGroup = Convert.ToInt32(Math.Ceiling(1.0 * PageCount / Displaysize)); //共多少页组
int CurrentGroup = (CurrentIndex - 1) / Displaysize + 1; //当前页组
int displaystart = (CurrentGroup - 1) * Displaysize + 1;
int displayend = displaystart + Displaysize;
if (displayend > (PageCount + 1))
{
displayend = PageCount + 1;
}
#region 显示后三的算法----------【新添加】
////显示后三的算法----------【新添加】
//if (PageCount > Displaysize && CurrentIndex > Displaysize - 3)
//{
// displaystart = CurrentIndex - (Displaysize - 4);
// displayend = CurrentIndex + 4;
// if (displayend - 1 >= PageCount)
// {
// displayend = PageCount + 1;
// }
//}
#endregion
//显示中间的算法----------【新添加】
if (PageCount > Displaysize && CurrentIndex >= Displaysize - ((Displaysize / 2) - 1))
{
displaystart = CurrentIndex - (Displaysize - (Displaysize / 2));
displayend = CurrentIndex + (Displaysize / 2);
if (displayend - 1 >= PageCount)
{
displayend = PageCount + 1;
}
}
//首页-------【新添加】
if (CurrentIndex != 1)
{
writer.RenderBeginTag(HtmlTextWriterTag.Span);
LinkText("【首页】", 1, writer);
writer.RenderEndTag();
}
else
{
//---【新添加】
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write("【首页】");
writer.RenderEndTag();
}
//上一页
if (CurrentIndex > 1)
{
writer.RenderBeginTag(HtmlTextWriterTag.Span);
if (string.IsNullOrEmpty(LastPageImageUrl))
{
LinkText(PageBarResource.Previous, CurrentIndex - 1, writer);
//LinkText("【上一页】", this.CurrentIndex - 1, writer);
}
else
{
LinkText(
"<img alt=\"" + PageBarResource.Previous + "\" src=\"" + LastPageImageUrl + "\" />",
CurrentIndex - 1, writer);
//LinkText("<img alt=\"" +"【上一页】" + "\" src=\"" + this.LastPageImageUrl + "\" />", this.CurrentIndex - 1, writer);
}
writer.RenderEndTag();
}
else
{
//---【新添加】
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write("【上一页】");
writer.RenderEndTag();
}
//上一组
if (CurrentGroup > 1 || displaystart != 1)
{
writer.AddAttribute(HtmlTextWriterAttribute.Title, "上"+Displaysize+"页");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
int index = CurrentIndex - Displaysize;
if (index < 1)
{
index = 1;
}
LinkText("<<", index, writer);
writer.RenderEndTag();
}
else
{
//---【新添加】
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write("<<");
writer.RenderEndTag();
}
string attr = string.Empty;
//显示数字
for (int i = displaystart; i < displayend; i++)
{
writer.RenderBeginTag(HtmlTextWriterTag.Span);
if (i != CurrentIndex)
{
LinkText(i.ToString() + " ", i, writer);
}
else
{
//当前页
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write(i + " ");
writer.RenderEndTag();
}
writer.RenderEndTag();
}
//下一组
if (displayend - 1 < PageCount)
{
writer.AddAttribute(HtmlTextWriterAttribute.Title, "下" + Displaysize + "页");
writer.RenderBeginTag(HtmlTextWriterTag.Span);
int index = CurrentIndex + Displaysize;
if (index > PageCount)
{
index = PageCount;
}
LinkText(">>", index, writer);
writer.RenderEndTag();
}
else
{
//---【新添加】
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write(">>");
writer.RenderEndTag();
}
//下一页
if (CurrentIndex < PageCount)
{
writer.RenderBeginTag(HtmlTextWriterTag.Span);
if (string.IsNullOrEmpty(NextPageImageUrl))
{
LinkText(PageBarResource.Next, CurrentIndex + 1, writer);
//LinkText("【下一页】", this.CurrentIndex + 1, writer);
}
else
{
LinkText("<img alt=\"" + PageBarResource.Next + "\" src=\"" + NextPageImageUrl + "\" />",
CurrentIndex + 1, writer);
//LinkText("<img alt=\"" + "【下一页】" + "\" src=\"" + this.NextPageImageUrl + "\" />", this.CurrentIndex + 1, writer);
}
writer.RenderEndTag();
}
else
{
//---【新添加】
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write("【下一页】");
writer.RenderEndTag();
}
//尾页-------【新添加】
if (CurrentIndex != PageCount)
{
writer.RenderBeginTag(HtmlTextWriterTag.Span);
LinkText("【尾页】", PageCount, writer);
writer.RenderEndTag();
}
else
{
//---【新添加】
writer.RenderBeginTag(HtmlTextWriterTag.Label);
writer.Write("【尾页】");
writer.RenderEndTag();
}
//跳转---【新添加】
if (PagerGroup > 1)
{
writer.AddAttribute(HtmlTextWriterAttribute.Type, "text");
writer.AddAttribute(HtmlTextWriterAttribute.Id, "goPage");
writer.AddAttribute(HtmlTextWriterAttribute.Value, Text);
writer.AddAttribute("onkeydown", "return PositiveInteger(this,event.keyCode);");
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, "10px");
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, "40px");
writer.AddStyleAttribute(HtmlTextWriterStyle.Position, "relative");
writer.AddStyleAttribute(HtmlTextWriterStyle.Top, "4px");
writer.AddAttribute(HtmlTextWriterAttribute.Maxlength, PageCount.ToString().Length.ToString());
writer.RenderBeginTag(HtmlTextWriterTag.Input);
writer.RenderEndTag();
writer.AddAttribute("onclick", "return validatePage(this);");
writer.AddAttribute(HtmlTextWriterAttribute.Href, "javascript:void(0)");
writer.RenderBeginTag(HtmlTextWriterTag.A);
writer.Write("【跳转】");
writer.RenderEndTag();
}
}
}
else
{
Visible = false;
}
}
#endregion
#region - LinkText -
private void LinkText(string text, int index, HtmlTextWriter write)
{
var strHtml = new StringBuilder();
//href
if (Mode == PageBarMode.Get)
{
#region = 获取和解析当前的url =
if (string.IsNullOrEmpty(UrlFormatString))
{
strHtml.Append(UrlHelper.Current.Path);
strHtml.Append("?");
NameValueCollection querys = Page.Request.QueryString;
foreach (string s in querys.Keys)
{
if (s != QueryStringKey)
{
strHtml.AppendFormat("{0}={1}&", s, Page.Server.UrlEncode(querys[s]));
}
}
strHtml.AppendFormat("{0}={1}", QueryStringKey, index);
}
else
{
strHtml.AppendFormat(UrlFormatString, index);
}
#endregion
}
else
{
上一篇: HTML5实战与剖析之Web存储机制(Web Storage)
下一篇: 数据库性能优化