Asp.net 分頁控制項

來源:互聯網
上載者:User

最近整理asp.net項目代碼,以前沒有記錄筆記的習慣,我要利用這次機會把項目常用的一些代碼整理歸檔,今天整理最通用的代碼,分頁控制項。

網上有很多分頁控制項,也很好用但是我這個分頁控制項是自己開發的,自認為還可以。這個分頁控制項大概步驟如下:

一、在項目中首先建立一個使用者控制項,命名為PageShow-1所示。                       

圖-1

二、在開啟的頁面當中添加一個asp:Literal控制項具體代碼如下:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="PageShow.ascx.cs" Inherits="Web.control.PageShow" %>

<asp:Literal ID="ltlPager" runat="server"></asp:Literal>

       三、編寫後台代碼實現分頁功能,一些代碼注釋我都寫在代碼中

using System;

using System.Collections;

using System.Configuration;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Text;

using System.Text.RegularExpressions;

namespace Web.control

{

    public partial class PageShow : System.Web.UI.UserControl

    {

        private int pageSize; //頁大小

        private int recordCount; //記錄總數

        private int page; //指當前頁碼

        private int pageCount;  //page總數

        private string url; //當前頁地址

        private int width; //控制項寬度

        private string cssClass; //控制項css類名

        private string align; //對齊

        private string pageHtml;

        private bool? enablePageInfo; //是否顯示分頁資訊

        private bool? enableJumpPage; //是否顯示跳轉資訊

        protected void Page_Load(object sender, EventArgs e)

        {

            pageCount = PageCount;

            page = CurrentPage;

            url = Url;

            string filename = System.IO.Path.GetFileName(HttpContext.Current.Request.Path);

            url = filename + url;

            width = Width;

            pageHtml += (width == 0) ? "<div class=\"" + CssClas + "\">" : "<div class=\"" + CssClas + "\" style=\"width:" + width + "px\">";

            if (EnablePageInfo == true) AppendPageInfo();

            pageHtml += (page <= 1) ? "<span class=\"disabled\">上一頁</span>" : "<a href=\"" + url.Replace("page=" + page, "page=" + (page - 1)) + "\" title=\"上一頁\" class=\"pagerPrev\">上一頁</a>";

            pageHtml += (page <= 1) ? "<span class=\"current\">" + page + "</span>" : "<a href=\"" + url.Replace("page=" + page, "page=1") + "\" title=\"跳轉到第1頁\">1</a>";

            int start = 2;

            int end = (pageCount < 10) ? pageCount : 10;

            if (page > 8)

            {

                pageHtml += "...";

                start = page - 4;

                int end1 = page + 5;

                end = (pageCount < end1) ? pageCount : end1;

            }

            for (int i = start; i < end; i++)

            {

                pageHtml += (i == page) ? "<span class=\"current\">" + i + "</span>" : "<a href=\"" + url.Replace("page=" + page, "page=" + i) + "\" title=\"跳轉到第" + i + "頁\">" + i + "</a>";

            }

            pageHtml += (page + 5 < pageCount) ? "..." : "";

            pageHtml += (page == pageCount) ? "<span class=\"current\">" + page + "</span>" : "<a href=\"" + url.Replace("page=" + page, "page=" + pageCount) + "\" title=\"跳轉到第" + pageCount + "頁\">" + pageCount + "</a>";

            pageHtml += (page == pageCount) ? "<span class=\"disabled\">下一頁</span>" : "<a href=\"" + url.Replace("page=" + page, "page=" + (page + 1)) + "\" title=\"下一頁\" class=\"pagerNext\">下一頁</a>";

            if (EnableJumpPage == true) AppendJumpPageScript();

            pageHtml += "</div>";

            ltlPager.Text = pageHtml;

        }

        private void AppendJumpPageScript()

        {

            pageHtml += "&nbsp;<span  class='jumpPage'>跳到第 <input id=\"txtPagebarJumpPage\" class=\"pagebarTextBox\" onfocus=\"this.value=''\" type=\"text\" value=\"" + page + "\" style=\"width:20px;\" /> 頁&nbsp;<input type=\"button\" class=\"pagerButton\" onclick=\"jumpPage();\" value=\"確定\" title=\"跳轉到指定頁\" /></span>" + System.Environment.NewLine;

            pageHtml += "<script type=\"text/javascript\">\n";

            pageHtml += " //<![CDATA[ \n";

            pageHtml += " function jumpPage(){ \n";

            pageHtml += "     var url; \r\n";

            pageHtml += "     var pageNo = document.getElementById('txtPagebarJumpPage').value; \n";

            pageHtml += "     if (document.URL.indexOf('page=') > 0) \r\n";

            pageHtml += "         url =  document.URL.replace('page=" + page + "','page='+pageNo); \n";

            pageHtml += "     else \n";

            pageHtml += "         url =  document.URL.indexOf('?') > 0 ? document.URL + '&amp;page='+ pageNo: document.URL + '?page='+pageNo; \n";

            pageHtml += "     location.href = url; \n";

            pageHtml += " } \r\n";

            pageHtml += " //]]> \r\n";

            pageHtml += "</script> \r\n";

        }

        private void AppendPageInfo()

        {

            pageHtml += "<span class=\"pageInfo\">第" + CurrentPage + "/" + PageCount + "頁" + System.Environment.NewLine + "</span>";

        }

        #region 受保護屬性

        /// <summary>

        /// 計算頁數

        /// </summary>

        private int PageCount

        {

            get

            {

                return (recordCount == 0) ? 1 : (int)(Math.Ceiling((double)recordCount / pageSize));

            }

        }

        /// <summary>

        /// 當前頁數

        /// </summary>

        private int CurrentPage

        {

            get

            {

                string query = Request.Url.Query;

                string pageString = "page=1";

                Regex regex = new Regex(@"(page=\d*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                Match match = regex.Match(query);

                if (match.Success)

                {

                    pageString = match.Groups[1].ToString();

                }

                if (pageString.IndexOf("=") > -1)

                {

                    string[] arrPage = pageString.Split(new Char[] { '=' });

                    page = Convert.ToInt32(arrPage[1]);

                }

                else

                {

                    page = 1;

                }

                if (page > PageCount) { page = PageCount; }

                if (page < 1) { page = 1; }

                return (int)page;

            }

        }

        /// <summary>

        /// 設定頁碼跳轉URL

        /// </summary>

        private string Url

        {

            get

            {

                string query = Request.Url.Query;

                Regex regex = new Regex(@"(page=\d*)", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                if (!regex.Match(query).Success) { query += (query.IndexOf("?") > -1 ? "&amp;page=1" : "?page=1"); }

                return query;

            }

        }

        #endregion

        #region  公用屬性

        /// <summary>

        /// 頁面大小

        /// </summary>

        public int PageSize

        {

            get { return (pageSize == 0) ? 10 : pageSize; }

            set { pageSize = value; }

        }

        /// <summary>

        /// 記錄總數

        /// </summary>

        public int RecordCount

        {

            get { return recordCount; }

            set { recordCount = value; }

        }

        /// <summary>

        /// 分頁樣式名稱

        /// </summary>

        public string CssClas

        {

            get { return (string.IsNullOrEmpty(cssClass)) ? "sabrosus" : cssClass; }

            set { cssClass = value; }

        }

        /// <summary>

        /// 對齊 center:置中;left:靠左對齊;right:靠右對齊

        /// </summary>

        public string Align

        {

            get

            {

                if (string.IsNullOrEmpty(align))

                    return "center";

                switch (align.ToLower())

                {

                    case "left":

                        return "left";

                    case "right":

                        return "right";

                    default:

                        return "center";

                }

            }

            set

            {

                align = value;

            }

        }

        public int Width

        {

            get { return width; }

            set { width = value; }

        }

        /// <summary>

        /// 是否顯示退轉頁面資訊

        /// </summary>

        public bool? EnableJumpPage

        {

            get { return (enableJumpPage == null) ? false : enableJumpPage; }

            set { enableJumpPage = value; }

        }

        /// <summary>

        /// 是否顯示頁面資訊,例如10/100共一百頁當前第10頁

        /// </summary>

        public bool? EnablePageInfo

        {

            get { return (enablePageInfo == null) ? false : enablePageInfo; }

            set { enablePageInfo = value; }

        }

        #endregion

    }

}

 

說一說這段代碼中的一些重點:

?的用處。在c#中的?是不常用的一個方法。

如果是一個?經常這樣用,資料類型?:表示可空類型,就是一種特殊的實值型別,它的值可以為null用於給變數設初值得時候,給變數賦值為null,而不是0。例如 int? a 表示給int類型變數賦null值

如果是兩個?則用於判斷並賦值,先判斷當前變數是否為null,如果是就可以賦後面的值,否則跳過。例如 obj = obj1 ?? new Object()

表示如果obj不為空白賦值obj1,否知賦值new Object()等價於如下代碼

if (obj == null)
      obj = new Object();
else
  obj = obj1;

四、css樣式美化

目前為止我已經開發了分頁控制項的大部分功能,但是分頁控制項現在很不美觀,需要我們編寫Css樣式進行美化,我編寫的Css檔案名稱叫Pagelist.css代碼如下,如果您感興趣可以自己編寫Css代碼進行美化。

.Pagelist{ height:30px; line-height:30px; text-align:right; margin-right:20px;}

.Pagelist a{padding:3px 8px; border:1px #CCC solid; margin:0px 3px;}

.pagerPrev{ padding:3px 8px; border:1px #CCC solid; margin:0px 3px;}

.current{padding:3px 8px; border:1px #CCC solid; margin:0px 3px; background:#F06; color:#FFF;}

.disabled{padding:3px 8px; border:1px #CCC solid; margin:0px 3px; background:#F6F6F6; color:#999;}

.pagebarTextBox{ border:1px #ccc solid;padding:3px 8px; }

.pagerButton{ border:1px #ccc solid;padding:3px 8px; }

五、控制項調用

Ok我們的控制項已經開發完畢,下面就是如何使用這個分頁控制項了,首先呢我們在頁面中引用這個控制項和Ccss樣式,具體代碼如下:

在頁面頭部引入控制項:

<%@ Register Src="../control/PageShow.ascx" TagName="PageShow" TagPrefix="uc1" %>

在head之間引入讓是表:

<link href="../skin/purple/Pagelist.css" rel="stylesheet" type="text/css" />

在需要顯示分頁的地方編寫控制項代碼:

      <div class="Pagelist">

        <uc1:PageShow ID="PageShow1" runat="server" CssClas="Pagelist" EnableJumpPage="true" EnablePageInfo="true" Width="960" />

        </div>

在後台編寫代碼實現分頁控制項的功能:

if (myp.recordCount > 20)

            {

                PageShow1.PageSize = 20;

                PageShow1.RecordCount = myp.recordCount;

            }

            else

            {

                PageShow1.Visible = false;

        }

這樣我們的分頁控制項就開發完畢了最終效果-2所示。

圖-2

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.