1,第一次全部把数据加载到内存中,然后再做分页,性能差,不推荐。
2,GridView自带分页
3,AspNetPager分页控件 这个是第三分控件需要下载,很好用
4,自己写分页
前三种就不介绍如何写了,网上很多,今天就来记录一下自己写的分页,不需要下载任何东西,全部都是代码完成。
我们的前台
<form id="form1" runat="server"> <div> //数据显示 <asp:Repeater ID="rpTest" runat="server"> <HeaderTemplate> <table style="width:80%"> <tr> <th style="width:20%">产品名</th> <th style="width:20%">单价</th> <th style="width:20%">分类ID</th> <th style="width:20%">你猜猜</th> </tr> </HeaderTemplate> <ItemTemplate> <tr> <td><%#Eval("[ProductName]") %></td> <td><%#Eval("[UnitPrice]") %></td> <td><%#Eval("[CategoryID]") %></td> <td><%#Eval("[QuantityPerUnit]") %></td> </tr> </ItemTemplate> <FooterTemplate> </table> </FooterTemplate> </asp:Repeater> </div> <br /> //分页 <div class="page"> <div class="details"> <span>每页<font><%=PageSize %></font>条</span> <span>共<font><%=PageCount %></font>条记录</span> </div> <div id="PageContent" class="paging" runat="server"> </div>
<script>
function Jump() { //跳转方法
window.location.href = "FenYeDemoOne.aspx?PageIndex=" + $("#textPage").val();
}
</script>
结构我们准备好了,然后把我们的样式给进来
/* 分页 --------------- */ .page{ width:100%; float:left; margin:-1px 0 0 0; background:#C9E4FF;} .details{ height:26px; float:left; padding:16px 0 16px 16px;} .details span{ height:26px; line-height:26px; float:left; padding:0 5px 0 0;} .details span font{ padding:0 5px;} .paging{ height:26px; float:right; padding:16px 16px 16px 0;} .paging a{ height:26px; float:left; line-height:26px; padding:0 9px; margin:0 0 0 6px; background:#FFF; border-radius:2px;} .paging span{ height:26px; float:left; line-height:26px; padding:0 10px; margin:0 0 0 6px;} .paging span.opt{ background:#009EFF; color:#FFF;} .paging a:hover{ text-decoration:none;} .paging input{ width:58px; height:26px; float:left; margin:0 0 0 6px; text-align:center;/* border:1px solid #D2D7DD; border-right:0px;*/} .paging a.res{ height:26px; float:left; color:#FFF; line-height:26px; margin:0px; border:0px; background:#009EFF; border-radius:0 2px 2px 0;} .paging a.res:hover{background:#00B6EC;} .paging span.cpb{ background:#009EFF; color:#FFF;} .paging span.disabled, .paging span.disabled{ height:26px; float:left; line-height:26px; padding:0 9px; margin:0 0 0 6px; background:#FFF;}
前台我们准备好了,我们来看后台,后台才是我们的主要
public int PageSize = 5; //每页显示多少条数据 public int PageIndex //当前页 { get { object obj = ViewState["PageIndex"]; return obj == null ? 1 : Convert.ToInt32(obj); } set { ViewState["PageIndex"] = value; } } public int PageCount //总记录数 { get { object obj = ViewState["PageCount"]; return obj == null ? 0 : Convert.ToInt32(obj); } set { ViewState["PageCount"] = value; } } public int TotalPage //总页数 { get { object obj = ViewState["TotalPage"]; return obj == null ? 1 : Convert.ToInt32(obj); } set { ViewState["TotalPage"] = value; } }
以上都基本会有
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { //点的是第几页 PageIndex = Request.QueryString["PageIndex"] == null ? 1 : Convert.ToInt32(Request.QueryString["PageIndex"].ToString()); BingData(); //绑定数据 } } void BingData() { //string textPage = hfPage.Value; 跳转的值 //总记录数 PageCount = Convert.ToInt32(SQLDB.SqlHelper.ExecuteScalar(conn, "select count(*) from Products")); //计算总页数 if (PageCount % PageSize == 0) { TotalPage = PageCount / PageSize; } else { TotalPage = (PageCount / PageSize) + 1; } //这里可以的话做个判断,跳转的时候如果输入大于最大的值就取最大值,小于最小值就取最小值 //if (!string.IsNullOrEmpty(textPage)) //{ // PageIndex = Convert.ToInt32(textPage); // if (Convert.ToInt32(textPage) > TotalPage) // { // PageIndex = TotalPage == 0 ? 1 : TotalPage; // } // if (Convert.ToInt32(textPage) <= 0) // { // PageIndex = 1; // } //} //SQL语句 string sql = "select top "+PageSize+"* from Products where ProductID not in (select top " + PageSize * (PageIndex - 1) + " ProductID from Products)"; rpTest.DataSource=SQLDB.SqlHelper.ExecuteDataSet(conn, sql); //数据源 rpTest.DataBind(); string pageUrl = Utils.CombUrlTxt("FenYeDemoOne.aspx", "PageIndex={0}", "__PageIndex__");//传过去的url,例如:XX.aspx?X=A&Y=B&Z=C.... PageContent.InnerHtml = Utils.OutPageList(this.PageSize, this.PageIndex, this.PageCount, pageUrl, 5); //分页方法,最后一个参数书店是中间显示多少个 }
后台主要是Utils里面的两个方法
/// <summary> /// 组合URL参数 /// </summary> /// <param name="_url">页面地址</param> /// <param name="_keys">参数名称</param> /// <param name="_values">参数值</param> /// <returns>String</returns> public static string CombUrlTxt(string _url, string _keys, params string[] _values) { StringBuilder urlParams = new StringBuilder(); try { string[] keyArr = _keys.Split(new char[] { ‘&‘ }); for (int i = 0; i < keyArr.Length; i++) { if (!string.IsNullOrEmpty(_values[i]) && _values[i] != "0") { _values[i] = UrlEncode(_values[i]); urlParams.Append(string.Format(keyArr[i], _values) + "&"); } } if (!string.IsNullOrEmpty(urlParams.ToString()) && _url.IndexOf("?") == -1) urlParams.Insert(0, "?"); } catch { return _url; } return _url + DelLastChar(urlParams.ToString(), "&"); //FenYeDemoOne.aspx?PageIndex=__PageIndex__
}
/// <summary> /// URL字符编码 /// </summary> public static string UrlEncode(string str) { if (string.IsNullOrEmpty(str)) { return ""; } str = str.Replace("‘", ""); return HttpContext.Current.Server.UrlEncode(str); }
/// <summary> /// 删除最后结尾的指定字符后的字符 /// </summary> public static string DelLastChar(string str, string strchar) { if (string.IsNullOrEmpty(str)) return ""; if (str.LastIndexOf(strchar) >= 0 && str.LastIndexOf(strchar) == str.Length - 1) { return str.Substring(0, str.LastIndexOf(strchar)); } return str; }
url里面的参数我们拼接好了
/// <summary> /// 返回分页页码 /// </summary> /// <param name="pageSize">页面大小</param> /// <param name="pageIndex">当前页</param> /// <param name="totalCount">总记录数</param> /// <param name="linkUrl">链接地址,__id__代表页码</param> /// <param name="centSize">中间页码数量</param> /// <returns></returns> public static string OutPageList(int pageSize, int pageIndex, int totalCount, string linkUrl, int centSize) { //计算页数 if (totalCount < 1 || pageSize < 1) { return ""; } int pageCount = totalCount / pageSize; //if (pageCount < 1) //{ // return ""; //} if (totalCount % pageSize > 0) { pageCount += 1; } if (pageCount < 1) { return ""; } StringBuilder pageStr = new StringBuilder(); string pageId = "__PageIndex__"; string firstBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex - 1).ToString()) + "\">?上一页</a>"; string lastBtn = "<a href=\"" + ReplaceStr(linkUrl, pageId, (pageIndex + 1).ToString()) + "\">下一页?</a>"; string firstStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, "1") + "\">1</a>"; string lastStr = "<a href=\"" + ReplaceStr(linkUrl, pageId, pageCount.ToString()) + "\">" + pageCount.ToString() + "</a>"; string textPage = "<input id=\"textPage\" value=\"" + pageIndex + "\" type=\"text\">"; string JumpPage = "<a class=\"res\" href=\"javascript:Jump();\">跳转</a>"; if (pageIndex <= 1) { firstBtn = "<span class=\"disabled\">?上一页</span>"; } if (pageIndex >= pageCount) { lastBtn = "<span class=\"disabled\">下一页?</span>"; } if (pageIndex == 1) { firstStr = "<span class=\"cpb\">1</span>"; } if (pageIndex == pageCount && pageCount > 1) { lastStr = "<span class=\"cpb\">" + pageCount.ToString() + "</span>"; } else if (pageCount == 1) { lastStr = ""; } int firstNum = pageIndex - (centSize / 2); //中间开始的页码 if (pageIndex < centSize) firstNum = 2; int lastNum = pageIndex + centSize - ((centSize / 2) + 1); //中间结束的页码 if (lastNum >= pageCount) lastNum = pageCount - 1; pageStr.Append(firstBtn + firstStr); if (pageIndex >= centSize) { pageStr.Append("<span>...</span>\n"); } for (int i = firstNum; i <= lastNum; i++) { if (i == pageIndex) { pageStr.Append("<span class=\"cpb\">" + i + "</span>"); } else { pageStr.Append("<a href=\"" + ReplaceStr(linkUrl, pageId, i.ToString()) + "\">" + i + "</a>"); } } if (pageCount - pageIndex > centSize - ((centSize / 2))) { pageStr.Append("<span>...</span>"); } pageStr.Append(lastStr + lastBtn); pageStr.Append(textPage); pageStr.Append(JumpPage); return pageStr.ToString(); }
/// <summary> /// 替换指定的字符串 /// </summary> /// <param name="originalStr">原字符串</param> /// <param name="oldStr">旧字符串</param> /// <param name="newStr">新字符串</param> /// <returns></returns> public static string ReplaceStr(string originalStr, string oldStr, string newStr) { if (string.IsNullOrEmpty(oldStr)) { return ""; } return originalStr.Replace(oldStr, newStr); }
显示效果
------------------------------------------------------------------------
到此我们手动分页已完成,这样页面是会刷新的,既然是刷新的就有无刷新的,下次分享。
时间: 2024-10-24 06:10:10