using System;
using System.Web;
using System.IO;
using System.Drawing;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Generic;
using System.ComponentModel;
using Winson.Framework.Utility;
using Winson.Framework.DBProviders;
using System.Text;

namespace Winson.Framework.Controls
{
    //Winson.SqlPager 分页控件
    //版本: 3.2
    //此控件必须与Winson.Framework框架一起使用
    //如有任何问题,欢迎到我们论坛发帖
    //http://bbs.szblogs.com

    #region 页面样式
    /// <summary>
    /// 页面样式设置
    /// </summary>
    public enum PagerStyle
    {
        /// <summary>
        /// 按钮样式为上下页箭头
        /// </summary>
        NextPrev,
        /// <summary>
        /// 按钮样式来下拉框页码
        /// </summary>
        NumericPages,
        /// <summary>
        /// 按钮和下拉框页码一起显示
        /// </summary>
        NextAndNumeric,
        /// <summary>
        /// 自定义样式，可自定文本
        /// </summary>
        CustomStyle,
        /// <summary>
        /// 自定义样式，可自定文本，同时显示下拉页码
        /// </summary>
        CustomAndNumeric,
        /// <summary>
        /// 无刷新箭头式按钮
        /// </summary>
        AjaxNext,
        /// <summary>
        /// 无刷新箭头式按钮加下拉页码
        /// </summary>
        AjaxNextAndNum,
        /// <summary>
        /// 无刷新下拉框按钮
        /// </summary>
        AjaxNumeric,
        /// <summary>
        /// 自定义无刷新分页
        /// </summary>
        AjaxCustomPages,
        /// <summary>
        /// 自定义无刷新和下拉框页码
        /// </summary>
        AjaxCustomAndNumeric,
        /// <summary>
        /// 数字页码样式
        /// </summary>
        NumPager,
        /// <summary>
        /// 使用自定义CSS产生的数字页码样式
        /// </summary>
        NumPagerWithCSS
    }
    /// <summary>
    /// 分页按钮的对齐方式
    /// </summary>
    public enum Align
    {
        Center = 0,
        Left = 1,
        Right = 2
    }
    /// <summary>
    /// 按钮的样式:Button-普通按钮;Image-图片,此时可直接填写图片地址
    /// </summary>
    public enum ButtonType
    {
        Button = 0,
        Image = 1
    }
    /// <summary>
    /// 超连文本的样式: Text-普通文本;Image-图片,此时可直接填写图片地址
    /// </summary>
    public enum LinkTextType
    {
        Text = 0,
        Image = 1
    }
    #endregion

    #region 排序方式
    /// <summary>
    /// 排序方式
    /// </summary>
    public enum SortStyle
    {
        /// <summary>
        /// 升序
        /// </summary>
        ASC,
        /// <summary>
        /// 降序
        /// </summary>
        DESC
    }
    #endregion

    #region 页面跳转事件
    /// <summary>
    /// 页面跳转事件
    /// </summary>
    public class PageChangedEventArgs : EventArgs
    {
        /// <summary>
        /// 当前页面索引
        /// </summary>
        public int OldPageIndex;
        /// <summary>
        /// 新页面索引
        /// </summary>
        public int NewPageIndex;
    }
    #endregion

    #region SqlPager分页控件
    /// <summary>
    /// SqlPager分页控件
    /// </summary>
    [DefaultProperty("SelectCommand")]
    [DefaultEvent("PageIndexChanged")]
    [ToolboxData("<{0}:SqlPager runat=\"server\" />")]
    public class SqlPager : WebControl, INamingContainer
    {
        #region  私有数据成员
        // ***********************************************************************
        // 私有成员
        private PagedDataSource _dataSource;
        private Control _controlToPaginate;
        static private DataSet _customDataSource = null;
        private int _totalCount;//总记录数
        private string CacheKeyName
        {
            get { return "Winson.Framework_" + UniqueID + "_Data"; }
        }

        private string CurrentPageText = "第{0}页/总{1}页 [每页{2}条/共{3}条记录]";
        private string NoPageSelectedText = "没有选择页面.";
        // ***********************************************************************
        #endregion

        #region 构造函数，初始化数据
        // ***********************************************************************
        /// <summary>
        /// 构造函数，初始化数据
        /// </summary>
        public SqlPager()
            : base()
        {
            _dataSource = null;
            _controlToPaginate = null;
            Font.Name = "verdana";
            Font.Size = FontUnit.Point(8);
            BackColor = Color.Gainsboro;
            ForeColor = Color.Black;
            BorderStyle = BorderStyle.Outset;
            BorderWidth = Unit.Parse("1px");
            SortStyle = SortStyle.ASC;
            PagerStyle = PagerStyle.NextPrev;
            CurrentPageIndex = 1;
            UseCustomDataSource = false;
            SelectCommand = "";
            ItemsPerPage = 10;
            TotalPages = 0;
            CacheDuration = Convert.ToInt32(Utility.Utility.ReadWebConfig("WF.CacheDuration", "60"));
        }
        // ***********************************************************************
        #endregion

        #region 公共程序接口，属性
        // ***********************************************************************
        /// <summary>
        /// 清除Cache中所有数据
        /// </summary>
        public void ClearCache()
        {
            Page.Cache.Remove(CacheKeyName);
        }
        // ***********************************************************************

        // ***********************************************************************
        #region 事件
        /// <summary>
        /// 页面跳转事件，当页面跳转到新页面时触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public delegate void PageChangedEventHandler(object sender, PageChangedEventArgs e);
        /// <summary>
        /// 页面跳转事件，当页面索引改变时触发
        /// </summary>
        public event PageChangedEventHandler PageIndexChanged;
        /// <summary>
        /// 页面跳转事件，当页面索引改变时触发
        /// </summary>
        /// <param name="e"></param>
        protected virtual void OnPageIndexChanged(PageChangedEventArgs e)
        {
            if (PageIndexChanged != null)
                PageIndexChanged(this, e);
        }
        #endregion
        // ***********************************************************************
        #region 分页按钮属性
        // ***********************************************************************
        /// <summary>
        /// 第一页的按钮样式
        /// </summary>
        [DefaultValue("第一页"), DescriptionAttribute("获取或设置第一页的文字或图片地址")]
        public string FirstButton
        {
            get
            {
                object savedState = ViewState["FirstButton"];
                return (savedState == null) ? "第一页" : (string)savedState;
            }
            set { ViewState["FirstButton"] = value; }
        }
        /// <summary>
        /// 上一页的按钮样式
        /// </summary>
        [DefaultValue("上一页"), DescriptionAttribute("获取或设置上一页的文字或图片地址")]
        public string PrveButton
        {
            get
            {
                object savedState = ViewState["PrveButton"];
                return (savedState == null) ? "上一页" : (string)savedState;
            }
            set { ViewState["PrveButton"] = value; }
        }
        /// <summary>
        /// 下一页的按钮样式
        /// </summary>
        [DefaultValue("下一页"), DescriptionAttribute("获取或设置下一页的文字或图片地址")]
        public string NextButton
        {
            get
            {
                object savedState = ViewState["NextButton"];
                return (savedState == null) ? "下一页" : (string)savedState;
            }
            set { ViewState["NextButton"] = value; }
        }
        /// <summary>
        /// 最后一页的按钮样式
        /// </summary>
        [DefaultValue("最后一页"), DescriptionAttribute("获取或设置最后一页的文字或图片地址")]
        public string LastButton
        {
            get
            {
                object savedState = ViewState["LastButton"];
                return (savedState == null) ? "最后一页" : (string)savedState;
            }
            set { ViewState["LastButton"] = value; }
        }

        #region============设置连接数字==========================
        [Category("分页控件所在元素的ID"), DefaultValue(""), DescriptionAttribute("分页控件所在元素的ID,以此ID来设置分页样式"), NotifyParentProperty(true)]
        public string PaterElementID
        {
            get
            {
                object savedState = ViewState["PaterElementID"];
                return (savedState == null) ? "" : (string)savedState;
            }
            set { ViewState["PaterElementID"] = value; }
        }
        [Category("控件连接文字或图片"), DefaultValue(""), DescriptionAttribute("获取或设置链接文字或图片地址的CSS类名"), NotifyParentProperty(true)]
        public string LinkTextCssClass
        {
            get
            {
                object savedState = ViewState["LinkTextCssClass"];
                return (savedState == null) ? "" : (string)savedState;
            }
            set { ViewState["LinkTextCssClass"] = value; }
        }
        [Category("控件连接文字或图片"), DefaultValue(LinkTextType.Text), DescriptionAttribute("获取或设置链接是文字或图片"), NotifyParentProperty(true)]
        public LinkTextType LinkTextType
        {
            get
            {
                object savedState = ViewState["LinkTextType"];
                return (savedState == null) ? LinkTextType.Text : (LinkTextType)savedState;
            }
            set { ViewState["LinkTextType"] = value; }
        }

        [Category("控件连接数字"), DefaultValue(""), DescriptionAttribute("获取或设置连接数字css样式"), NotifyParentProperty(true)]
        public string LinkNumberCssClass
        {
            get
            {
                object savedState = ViewState["LinkNumberCssClass"];
                return (savedState == null) ? "" : (string)savedState;
            }
            set { ViewState["LinkNumberCssClass"] = value; }
        }
        [Category("控件连接数字"), DescriptionAttribute("获取或设置当前连接数字的颜色"), NotifyParentProperty(true)]
        public Color CurrentNumberColor
        {
            get
            {
                object savedState = ViewState["CurrentNumberColor"];
                return (savedState == null) ? Color.Red : (Color)savedState;
            }
            set { ViewState["CurrentNumberColor"] = value; }
        }
        [Category("控件连接数字"), DefaultValue(5), DescriptionAttribute("设置或获取分页左边要显示的页码数"), NotifyParentProperty(true)]
        public int LeftPageSize
        {
            get
            {
                object savedState = ViewState["LeftPageSize"];
                return (savedState == null) ? 5 : (int)savedState;
            }
            set { ViewState["LeftPageSize"] = value; }
        }
        [Category("控件连接数字"), DefaultValue(5), DescriptionAttribute("设置或获取分页右边要显示的页码数"), NotifyParentProperty(true)]
        public int RightPageSize
        {
            get
            {
                object savedState = ViewState["RightPageSize"];
                return (savedState == null) ? 5 : (int)savedState;
            }
            set { ViewState["RightPageSize"] = value; }
        }

        [Category("控件连接数字"), DefaultValue("16px"), DescriptionAttribute("设置或获取连接数字单元格的宽度"), NotifyParentProperty(true)]
        public Unit LinkNumberWidth
        {
            get
            {
                object savedState = ViewState["LinkNumberWidth"];
                return (savedState == null) ? new Unit("16px") : (Unit)savedState;
            }
            set { ViewState["LinkNumberWidth"] = value; }
        }

        [Category("控件连接数字"), DefaultValue("16px"), DescriptionAttribute("设置或获取连接数字单元格的高度"), NotifyParentProperty(true)]
        public Unit LinkNumberHeight
        {
            get
            {
                object savedState = ViewState["LinkNumberHeight"];
                return (savedState == null) ? new Unit("16px") : (Unit)savedState;
            }
            set { ViewState["LinkNumberHeight"] = value; }
        }
        #endregion

        #region =============分页显示的Table属性===========================

        /// <summary>
        /// 获取或设置转到文本框和按钮是否显示
        /// </summary>
        [Category("控件外观"), DefaultValue(true), DescriptionAttribute("获取或设置转到文本框和按钮是否显示"), NotifyParentProperty(true)]
        public bool ButtonAndTextBoxVisible
        {
            get
            {
                object savedState = ViewState["ButtonAndTextBoxVisible"];
                return (savedState == null) ? true : (bool)savedState;
            }
            set { ViewState["ButtonAndTextBoxVisible"] = value; }
        }

        /// <summary>
        /// 设置或获取控件的宽度
        /// </summary>
        [Category("控件设置"), DefaultValue("600px"), DescriptionAttribute("设置或获取控件的宽度")]
        public override Unit Width
        {
            get
            {
                object savedState = ViewState["Width"];
                return (savedState == null) ? new Unit("600px") : (Unit)savedState;
            }
            set { ViewState["Width"] = value; }
        }

        /// <summary>
        /// 设置或获取控件的高度
        /// </summary>
        [Category("控件设置"), DefaultValue("28px"), DescriptionAttribute("设置或获取控件的高度")]
        public override Unit Height
        {
            get
            {
                object savedState = ViewState["Height"];
                return (savedState == null) ? new Unit("28px") : (Unit)savedState;
            }
            set { ViewState["Height"] = value; }
        }

        /// <summary>
        /// 设置或获取控件的边框宽度
        /// </summary>
        [Category("控件设置"), DefaultValue("0px"), DescriptionAttribute("设置或获取控件的边框宽度")]
        public override Unit BorderWidth
        {
            get
            {
                object savedState = ViewState["BorderWidth"];
                return (savedState == null) ? new Unit("0px") : (Unit)savedState;
            }
            set { ViewState["BorderWidth"] = value; }
        }

        /// <summary>
        /// 设置或获取表格的间距值
        /// </summary>
        [Category("控件设置"), DefaultValue("1px"), DescriptionAttribute("设置或获取表格的间距值")]
        public Unit CellSpacing
        {
            get
            {
                object savedState = ViewState["CellSpacing"];
                return (savedState == null) ? new Unit("1px") : (Unit)savedState;
            }
            set { ViewState["CellSpacing"] = value; }
        }

        /// <summary>
        /// 设置或获取表格的填充值
        /// </summary>
        [Category("控件设置"), DefaultValue("0px"), DescriptionAttribute("设置或获取表格的填充值")]
        public Unit CellPadding
        {
            get
            {
                object savedState = ViewState["CellPadding"];
                return (savedState == null) ? new Unit("0px") : (Unit)savedState;
            }
            set { ViewState["CellPadding"] = value; }
        }

        /// <summary>
        /// 获取或设置控件的水平对齐方式。可以为：Center，Left，Right。
        /// </summary>
        [Category("控件设置"), DefaultValue(Align.Center),
        DescriptionAttribute("获取或设置控件的水平对齐方式。可以为：Center，Left，Right。")
        ]
        public Align Align
        {
            get
            {
                object savedState = ViewState["Align"];
                return (savedState == null) ? Align.Center : (Align)savedState;
            }
            set { ViewState["Align"] = value; }
        }

        /// <summary>
        /// 鼠标放到控件上时显示的工具提示
        /// </summary>
        [Category("控件设置"), DefaultValue("深圳博客技术论坛"), DescriptionAttribute("鼠标放到控件上时显示的工具提示")]
        public override string ToolTip
        {
            get
            {
                object savedState = ViewState["ToolTip"];
                return (savedState == null) ? "深圳博客技术论坛" : (string)savedState;
            }
            set { ViewState["ToolTip"] = value; }
        }

        /// <summary>
        /// 设置或获取控件的边框颜色
        /// </summary>
        [Category("控件设置"), DescriptionAttribute("设置或获取控件的边框颜色")]
        public override Color BorderColor
        {
            get
            {
                object savedState = ViewState["BorderColor"];
                return (savedState == null) ? Color.Empty : (Color)savedState;
            }
            set { ViewState["BorderColor"] = value; }
        }

        /// <summary>
        /// 设置或获取控件的背景颜色
        /// </summary>
        [Category("控件设置"), DescriptionAttribute("设置或获取控件的背景颜色")]
        public override Color BackColor
        {
            get
            {
                object savedState = ViewState["BackColor"];
                return (savedState == null) ? Color.Empty : (Color)savedState;
            }
            set { ViewState["BackColor"] = value; }
        }

        /// <summary>
        /// 应用于该控件的CSS类名
        /// </summary>
        [Category("控件设置"), DefaultValue(""), DescriptionAttribute("应用于该控件的CSS类名")]
        public override string CssClass
        {
            get
            {
                object savedState = ViewState["CssClass"];
                return (savedState == null) ? "" : (string)savedState;
            }
            set { ViewState["CssClass"] = value; }
        }

        /// <summary>
        /// 指示该控件是否呈现并被呈现出来
        /// </summary>
        [Category("控件设置"), DefaultValue(true), DescriptionAttribute("指示该控件是否呈现并被呈现出来")]
        public override bool Visible
        {
            get
            {
                object savedState = ViewState["Visible"];
                return (savedState == null) ? true : (bool)savedState;
            }
            set { ViewState["Visible"] = value; }
        }

        /// <summary>
        /// 获取或设置转到按钮文本
        /// </summary>
        [Category("控件外观"), DefaultValue("GO"), DescriptionAttribute("获取或设置转到按钮文本或图片"), NotifyParentProperty(true)]
        public string ButtonText
        {
            get
            {
                object savedState = ViewState["ButtonText"];
                return (savedState == null) ? "GO" : (string)savedState;
            }
            set { ViewState["ButtonText"] = value; }
        }
        /// <summary>
        /// 获取或设置转到按钮类型。可以为：Button，Image。
        /// </summary>
        [Category("控件外观"), DefaultValue(ButtonType.Button),
        DescriptionAttribute("获取或设置转到按钮类型。可以为：Button，Image。")
        ]
        public ButtonType ButtonType
        {
            get
            {
                object savedState = ViewState["ButtonType"];
                return (savedState == null) ? ButtonType.Button : (ButtonType)savedState;
            }
            set { ViewState["ButtonType"] = value; }
        }

        [Category("控件外观"), DefaultValue(4), DescriptionAttribute("获取或设置文本框宽度"), NotifyParentProperty(true)]
        public int TextBoxWidth
        {
            get
            {
                object savedState = ViewState["TextBoxWidth"];
                return (savedState == null) ? 4 : Convert.ToInt32(savedState);
            }
            set { ViewState["TextBoxWidth"] = value; }
        }


        #endregion

        #endregion

        /// <summary>
        /// 缓存持续时间
        /// </summary>
        [Description("设置缓存的持续时间，默认为60秒")]
        public int CacheDuration
        {
            get { return Convert.ToInt32(ViewState["CacheDuration"]); }
            set { ViewState["CacheDuration"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 显示统计页数模式
        /// </summary>
        [Description("显示统计页数模式,0:'第{0}页/总{1}页'  1:'第{0}页/总{1}页 [每页{2}条/共{3}条记录]'    默认不设置:'不显示'")]
        public int ShowCount
        {
            get
            {
                object savedState = ViewState["ShowCount"];
                return (savedState == null) ? -1 : (int)savedState;
            }
            set { ViewState["ShowCount"] = value; }
        }
        // ***********************************************************************


        // ***********************************************************************
        /// <summary>
        /// 设置排序方式，升、降（默认为升序）
        /// </summary>
        [Description("设置排序方式，升、降（默认为升序）")]
        public SortStyle SortStyle
        {
            get { return (SortStyle)ViewState["SortStyle"]; }
            set { ViewState["SortStyle"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 分页样式设置，显示上、下分页还是下拉框页码
        /// </summary>
        [Description("设置分页按钮样式")]
        public PagerStyle PagerStyle
        {
            get { return (PagerStyle)ViewState["PagerStyle"]; }
            set { ViewState["PagerStyle"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置客户端的分页函数,for AJAX
        /// </summary>
        [Description("设置客户端的分页函数,for AJAX")]
        public string ClientSetPager
        {
            get
            {
                object clientSetPager = ViewState["ClientSetPager"];
                return (clientSetPager == null) ? "setPageTo" : (string)clientSetPager;
            }
            set { ViewState["ClientSetPager"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置关联控件的ID
        /// </summary>
        [Description("设置关联控件的ID")]
        public string ControlToPaginate
        {
            get { return Convert.ToString(ViewState["ControlToPaginate"]); }
            set { ViewState["ControlToPaginate"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置所在的父级元素的ID
        /// </summary>
        [Description("设置所在的父级元素的ID")]
        public string PaternalID
        {
            get { return Convert.ToString(ViewState["PaternalID"]); }
            set { ViewState["PaternalID"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置每页显示记录数
        /// </summary>
        [Description("每页显示记录数")]
        public int ItemsPerPage
        {
            get { return Convert.ToInt32(ViewState["ItemsPerPage"]); }
            set { ViewState["ItemsPerPage"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置当前页面索引
        /// </summary>
        [Description("当前页面索引")]
        public int CurrentPageIndex
        {
            get { return Convert.ToInt32(ViewState["CurrentPageIndex"]); }
            set { ViewState["CurrentPageIndex"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置查询语句
        /// </summary>
        [Description("设置查询语句")]
        public string SelectCommand
        {
            get { return Convert.ToString(ViewState["SelectCommand"]); }
            set { ViewState["SelectCommand"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置排序信息
        /// </summary>
        [Description("设置排序关键字.)")]
        public string SortField
        {
            get { return Convert.ToString(ViewState["SortKeyField"]); }
            set { ViewState["SortKeyField"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 获取页面大小，总共需显示的记录数
        /// </summary>
        [Browsable(false)]
        public int PageCount
        {
            get { return TotalPages; }
        }
        /// <summary>
        /// 是否使用自定义数据源
        /// </summary>
        [Description("是否使用自定义数据源")]
        public bool UseCustomDataSource
        {
            get { return Convert.ToBoolean(ViewState["UseCustomDataSource"]); }
            set { ViewState["UseCustomDataSource"] = value; }
        }
        /// <summary>
        /// 设置自定义数据源
        /// </summary>
        [Browsable(false)]
        public DataSet CustomDataSource
        {
            set { _customDataSource = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置获取总页数
        /// </summary>
        public int TotalPages
        {
            get { return Convert.ToInt32(ViewState["TotalPages"]); }
            set { ViewState["TotalPages"] = value; }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 设置获取母板页当前子页面ID
        /// </summary>
        [Description("设置获取母板页当前子页面ID")]
        public string ContentPlaceHolderID
        {
            get { return Convert.ToString(ViewState["ContentPlaceHolderID"]); }
            set { ViewState["ContentPlaceHolderID"] = value; }
        }

        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 数据绑定，取出并排序数据
        /// </summary>
        public override void DataBind()
        {
            // 开始绑定事件
            base.DataBind();

            // 是否生成子控件　Controls must be recreated after data binding 
            ChildControlsCreated = false;

            // 确保控件存在并且是一个合法的数据容器控件
            if (ControlToPaginate == "")
                return;

            _controlToPaginate = Page.FindControl(ControlToPaginate);

            if (_controlToPaginate == null)
            {
                if (ContentPlaceHolderID != "")
                    //如果使用母板页，则从母板页里获取
                    _controlToPaginate = ((ContentPlaceHolder)Page.Master.FindControl(ContentPlaceHolderID)).FindControl(ControlToPaginate);
                if (_controlToPaginate == null)
                    return;
            }

            if (!(_controlToPaginate is BaseDataList || _controlToPaginate is GridView || _controlToPaginate is ListControl || _controlToPaginate is Repeater))
                return;

            // 确保有查询条件
            if (UseCustomDataSource && _customDataSource == null)
                return;
            if (SelectCommand == "" && !UseCustomDataSource)
                return;

            // 获取数据
            FetchAllData();

            // 向控件绑定数据
            BaseDataList baseDataListControl = null;
            ListControl listControl = null;
            Repeater rp = null;
            GridView gv = null;
            if (_controlToPaginate is BaseDataList)
            {
                baseDataListControl = (BaseDataList)_controlToPaginate;
                baseDataListControl.DataSource = _dataSource;
                baseDataListControl.DataBind();
                return;
            }
            if (_controlToPaginate is ListControl)
            {
                listControl = (ListControl)_controlToPaginate;
                listControl.Items.Clear();
                listControl.DataSource = _dataSource;
                listControl.DataBind();
                return;
            }
            if (_controlToPaginate is Repeater)
            {
                rp = (Repeater)_controlToPaginate;
                rp.DataSource = _dataSource;
                rp.DataBind();
            }
            if (_controlToPaginate is GridView)
            {
                gv = (GridView)_controlToPaginate;
                gv.DataSource = _dataSource;
                gv.DataBind();
            }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 将内容呈现在客户端
        /// </summary>
        /// <param name="output"></param> 
        protected override void Render(HtmlTextWriter output)
        {
            // If in design-mode ensure that child controls have been created.
            // Child controls are not created at this time in design-mode because
            // there's no pre-render stage. Do so for composite controls like this 
            if (Site != null && Site.DesignMode)
                CreateChildControls();

            base.Render(output);
        }
        /// <summary>
        /// 将控件呈现于页面，用于AJAX分页
        /// </summary>
        /// <param name="output"></param>
        public override void RenderControl(HtmlTextWriter output)
        {
            CreateChildControls();
            base.Render(output);
        }

        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 重写CreateChildControls，输出HTML代码
        /// </summary>
        protected override void CreateChildControls()
        {
            Controls.Clear();
            ClearChildViewState();
            if (PagerStyle == PagerStyle.AjaxCustomPages)
                BuildAjaxControl();
            else
                BuildControlHierarchy();
        }
        // ***********************************************************************
        #endregion

        #region 私有方法
        // ***********************************************************************
        #region 创建导航按钮
        /// <summary>
        /// 创建分页导航按钮
        /// </summary>
        private void BuildControlHierarchy()
        {
            // 创建一个表 (一行，二列)
            Table t = new Table();
            t.Font.Name = Font.Name;
            t.Font.Size = Font.Size;
            t.BorderStyle = BorderStyle;
            t.BorderWidth = BorderWidth;
            t.BorderColor = BorderColor;
            t.Width = Width;
            t.Height = Height;
            t.BackColor = BackColor;
            t.ForeColor = ForeColor;
            //指定样式名称
            t.CssClass = "PageButton";

            // 创建空行与列
            TableRow breakRow = new TableRow();
            t.Rows.Add(breakRow);
            TableCell breakCell = new TableCell();
            breakCell.Height = Unit.Pixel(10);
            breakRow.Cells.Add(breakCell);


            // 创建行
            TableRow row = new TableRow();
            t.Rows.Add(row);

            // 为页索引创建列
            TableCell cellPageDesc = new TableCell();
            cellPageDesc.HorizontalAlign = HorizontalAlign.Left;
            //cellPageDesc.Width = Unit.Percentage(80);
            if (PagerStyle == PagerStyle.NumPager)
                this.ShowCount = 2;
            BuildCurrentPage(cellPageDesc);
            row.Cells.Add(cellPageDesc);

            // 为导航条创建列
            TableCell cellNavBar = new TableCell();
            cellNavBar.HorizontalAlign = HorizontalAlign.Right;
            switch (PagerStyle)
            {
                case PagerStyle.NextPrev:
                    BuildNextPrevUI(cellNavBar);
                    break;
                case PagerStyle.NumericPages:
                    BuildNumericPagesUI(cellNavBar);
                    break;
                case PagerStyle.NextAndNumeric:
                    BuildNextPrevUI(cellNavBar);
                    cellNavBar.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;选择页数："));
                    BuildNumericPagesUI(cellNavBar);
                    break;
                case PagerStyle.CustomStyle:
                    BuildCustomUI(cellNavBar);
                    break;
                case PagerStyle.CustomAndNumeric:
                    BuildCustomUI(cellNavBar);
                    cellNavBar.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;选择页数："));
                    BuildNumericPagesUI(cellNavBar);
                    break;
                case PagerStyle.AjaxNext:
                    BuildAjaxNextUI(cellNavBar);
                    break;
                case PagerStyle.AjaxNumeric:
                    BuildAjaxNumericUI(cellNavBar);
                    break;
                case PagerStyle.AjaxCustomPages:
                    BuildAjaxCustomUI(cellNavBar);
                    break;
                case PagerStyle.AjaxCustomAndNumeric:
                    BuildAjaxCustomUI(cellNavBar);
                    cellNavBar.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;选择页数："));
                    BuildAjaxNumericUI(cellNavBar);
                    break;
                case PagerStyle.AjaxNextAndNum:
                    BuildAjaxNextUI(cellNavBar);
                    cellNavBar.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;选择页数："));
                    BuildAjaxNumericUI(cellNavBar);
                    break;
                case PagerStyle.NumPager:
                    BuildNumPageUI(cellNavBar);
                    break;
                case PagerStyle.NumPagerWithCSS:
                    BuildNumPageUIWithPagerCSS(cellNavBar);
                    break;

            }
            row.Cells.Add(cellNavBar);

            // 将表加入到控件树
            Controls.Add(t);
        }
        /// <summary>
        /// 为Ajax创建自定义分页导航按钮
        /// </summary>
        public void BuildAjaxControl()
        {
            // 创建一个表 (一行，二列)

            Table t = new Table();
            t.Font.Name = Font.Name;
            t.Font.Size = Font.Size;
            t.BorderStyle = BorderStyle;
            t.BorderWidth = BorderWidth;
            t.BorderColor = BorderColor;
            t.Width = Width;
            t.Height = Height;
            t.BackColor = BackColor;
            t.ForeColor = ForeColor;
            //指定样式名称
            t.CssClass = "PageButton";

            // 创建空行与列
            TableRow breakRow = new TableRow();
            t.Rows.Add(breakRow);
            TableCell breakCell = new TableCell();
            breakCell.Height = Unit.Pixel(10);
            breakRow.Cells.Add(breakCell);

            // 创建行
            TableRow row = new TableRow();
            t.Rows.Add(row);

            // 为页索引创建列
            TableCell cellPageDesc = new TableCell();
            cellPageDesc.HorizontalAlign = HorizontalAlign.Left;
            BuildCurrentPage(cellPageDesc);
            row.Cells.Add(cellPageDesc);

            // 为导航条创建列
            TableCell cellNavBar = new TableCell();
            cellNavBar.HorizontalAlign = HorizontalAlign.Right;
            switch (PagerStyle)
            {
                case PagerStyle.AjaxNext:
                    BuildAjaxNextUI(cellNavBar);
                    break;
                case PagerStyle.AjaxNumeric:
                    BuildAjaxNumericUI(cellNavBar);
                    break;
                case PagerStyle.AjaxCustomPages:
                    BuildAjaxCustomUI(cellNavBar);
                    break;
                case PagerStyle.AjaxCustomAndNumeric:
                    BuildAjaxCustomUI(cellNavBar);
                    cellNavBar.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;选择页数："));
                    BuildAjaxNumericUI(cellNavBar);
                    break;
                case PagerStyle.AjaxNextAndNum:
                    BuildAjaxNextUI(cellNavBar);
                    cellNavBar.Controls.Add(new LiteralControl("&nbsp;&nbsp;&nbsp;&nbsp;选择页数："));
                    BuildAjaxNumericUI(cellNavBar);
                    break;
            }
            row.Cells.Add(cellNavBar);

            Controls.Add(t);
            //return t;
        }
        #endregion
        // ***********************************************************************

        // ***********************************************************************        
        #region 无刷新按钮
        /// <summary>
        /// 创建箭头按钮
        /// </summary>
        /// <param name="cell">表格列对象</param>
        private void BuildAjaxNextUI(TableCell cell)
        {
            bool isValidPage = (CurrentPageIndex >= 1 && CurrentPageIndex <= TotalPages);
            bool canMoveBack = (CurrentPageIndex > 1);
            bool canMoveForward = (CurrentPageIndex <= TotalPages - 1);

            // 呈现 > 按钮
            LinkButton first = new LinkButton();
            first.ID = "First";
            first.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(1) + ");return false;");
            first.Font.Name = "webdings";
            first.Font.Size = FontUnit.Medium;
            first.ForeColor = ForeColor;
            first.ToolTip = "第一页";
            first.Text = "7";
            first.Enabled = isValidPage && canMoveBack;
            cell.Controls.Add(first);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            // 呈现 << 按钮
            LinkButton prev = new LinkButton();
            prev.ID = "Prev";
            prev.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(CurrentPageIndex - 1) + ");return false;");
            prev.Font.Name = "webdings";
            prev.Font.Size = FontUnit.Medium;
            prev.ForeColor = ForeColor;
            prev.ToolTip = "上一页";
            prev.Text = "3";
            prev.Enabled = isValidPage && canMoveBack;
            cell.Controls.Add(prev);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            // 呈现 > 按钮
            LinkButton next = new LinkButton();
            next.ID = "Next";
            next.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(CurrentPageIndex + 1) + ");return false;");
            next.Font.Name = "webdings";
            next.Font.Size = FontUnit.Medium;
            next.ForeColor = ForeColor;
            next.ToolTip = "下一页";
            next.Text = "4";
            next.Enabled = isValidPage && canMoveForward;
            cell.Controls.Add(next);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            // 呈现 >> 按钮
            LinkButton last = new LinkButton();
            last.ID = "Last";
            last.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(TotalPages) + ");return false;");
            last.Font.Name = "webdings";
            last.Font.Size = FontUnit.Medium;
            last.ForeColor = ForeColor;
            last.ToolTip = "最后一页";
            last.Text = "8";
            last.Enabled = isValidPage && canMoveForward;
            cell.Controls.Add(last);
        }
        /// <summary>
        /// 无刷新分页按钮
        /// </summary>
        /// <param name="cell">表格列对象</param>
        private void BuildAjaxCustomUI(TableCell cell)
        {
            bool isValidPage = (CurrentPageIndex >= 1 && CurrentPageIndex <= TotalPages);
            bool canMoveBack = (CurrentPageIndex > 1);
            bool canMoveForward = (CurrentPageIndex <= TotalPages - 1);

            LinkButton first = new LinkButton();
            first.ID = "First";
            //first.Click += new EventHandler(first_Click);
            if (isValidPage && canMoveBack)
                first.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(1) + ");return false;");
            //first.Font.Name = "webdings";
            first.Font.Size = Font.Size;
            first.ForeColor = ForeColor;
            first.ToolTip = "第一页";
            first.Text = FirstButton;
            first.Enabled = isValidPage && canMoveBack;
            if (!(first.Enabled))
                first.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(first);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            LinkButton prev = new LinkButton();
            prev.ID = "Prev";
            //prev.Click += new EventHandler(prev_Click);
            if (isValidPage && canMoveBack)
                prev.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(CurrentPageIndex - 1) + ");return false;");
            //prev.Font.Name = "webdings";
            prev.Font.Size = Font.Size;
            prev.ForeColor = ForeColor;
            prev.ToolTip = "上一页";
            prev.Text = PrveButton;
            prev.Enabled = isValidPage && canMoveBack;
            if (!(prev.Enabled))
                prev.Style.Add("color", "#A0A0A0");

            cell.Controls.Add(prev);

            cell.Controls.Add(new LiteralControl("&nbsp;"));

            LinkButton next = new LinkButton();
            next.ID = "Next";
            //next.Click += new EventHandler(next_Click);
            if (isValidPage && canMoveForward)
                next.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(CurrentPageIndex + 1) + ");return false;");
            //next.Font.Name = "webdings";
            next.Font.Size = Font.Size;
            next.ForeColor = ForeColor;
            next.ToolTip = "下一页";
            next.Text = NextButton;
            next.Enabled = isValidPage && canMoveForward;
            if (!(next.Enabled))
                next.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(next);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));


            LinkButton last = new LinkButton();
            last.ID = "Last";
            if (isValidPage && canMoveForward)
                last.Attributes.Add("onclick", ClientSetPager + "('" + PaternalID + "'," + Convert.ToString(TotalPages) + ");return false;");
            last.Font.Size = Font.Size;
            last.ForeColor = ForeColor;
            last.ToolTip = "最后一页";
            last.Text = LastButton;
            last.Enabled = isValidPage && canMoveForward;
            if (!(last.Enabled))
                last.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(last);
        }
        /// <summary>
        /// 无刷新下拉框页码显示
        /// </summary>
        /// <param name="cell">列对象</param>
        private void BuildAjaxNumericUI(TableCell cell)
        {
            // 呈现一个下拉框列表
            DropDownList pageList = new DropDownList();
            pageList.ID = "PageList";
            pageList.AutoPostBack = false;
            //pageList.SelectedIndexChanged += new EventHandler(PageList_Click);
            pageList.Attributes.Add("onchange", ClientSetPager + "('" + PaternalID + "',this.value);return false;");
            pageList.Font.Name = Font.Name;
            pageList.Font.Size = Font.Size;
            pageList.ForeColor = ForeColor;

            // 当无分页数据时，设置一个默认值
            if (TotalPages <= 0 || CurrentPageIndex == -1)
            {
                pageList.Items.Add("无分页");
                pageList.Enabled = false;
                pageList.SelectedIndex = 0;
                pageList.Style.Add("color", "#A0A0A0");
            }
            else // 移动列表
            {
                for (int i = 1; i <= TotalPages; i++)
                {
                    ListItem item = new ListItem(i.ToString(), i.ToString());
                    pageList.Items.Add(item);
                }
                pageList.SelectedIndex = CurrentPageIndex - 1;
            }
            cell.Controls.Add(pageList);
        }
        #endregion

        #region 服务器后台运行按钮
        /// <summary>
        /// 创建自定义按钮
        /// </summary>
        /// <param name="cell">表格列对象</param>
        private void BuildCustomUI(TableCell cell)
        {
            bool isValidPage = (CurrentPageIndex >= 1 && CurrentPageIndex <= TotalPages);
            bool canMoveBack = (CurrentPageIndex > 1);
            bool canMoveForward = (CurrentPageIndex <= TotalPages - 1);

            LinkButton first = new LinkButton();
            first.ID = "First";
            if (isValidPage && canMoveBack)
                first.Click += new EventHandler(first_Click);
            //first.Font.Name = "webdings";
            first.Font.Size = Font.Size;
            first.ForeColor = ForeColor;
            first.ToolTip = "第一页";
            first.Text = FirstButton;
            first.Enabled = isValidPage && canMoveBack;
            if (!(first.Enabled))
                first.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(first);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            LinkButton prev = new LinkButton();
            prev.ID = "Prev";
            if (isValidPage && canMoveBack)
                prev.Click += new EventHandler(prev_Click);
            //prev.Font.Name = "webdings";
            prev.Font.Size = Font.Size;
            prev.ForeColor = ForeColor;
            prev.ToolTip = "上一页";
            prev.Text = PrveButton;
            prev.Enabled = isValidPage && canMoveBack;
            if (!(prev.Enabled))
                prev.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(prev);

            cell.Controls.Add(new LiteralControl("&nbsp;"));

            LinkButton next = new LinkButton();
            next.ID = "Next";
            if (isValidPage && canMoveForward)
                next.Click += new EventHandler(next_Click);
            //next.Font.Name = "webdings";
            next.Font.Size = Font.Size;
            next.ForeColor = ForeColor;
            next.ToolTip = "下一页";
            next.Text = NextButton;
            next.Enabled = isValidPage && canMoveForward;
            if (!(next.Enabled))
                next.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(next);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));


            LinkButton last = new LinkButton();
            last.ID = "Last";
            if (isValidPage && canMoveForward)
                last.Click += new EventHandler(last_Click);
            //last.Font.Name = "webdings";
            last.Font.Size = Font.Size;
            last.ForeColor = ForeColor;
            last.ToolTip = "最后一页";
            last.Text = LastButton;
            last.Enabled = isValidPage && canMoveForward;
            if (!(last.Enabled))
                last.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(last);
        }

        /// <summary>
        /// 创建箭头按钮
        /// </summary>
        /// <param name="cell">表格列对象</param>
        private void BuildNextPrevUI(TableCell cell)
        {
            bool isValidPage = (CurrentPageIndex >= 1 && CurrentPageIndex <= TotalPages);
            bool canMoveBack = (CurrentPageIndex > 1);
            bool canMoveForward = (CurrentPageIndex <= TotalPages - 1);

            // 呈现 > 按钮
            LinkButton first = new LinkButton();
            first.ID = "First";
            if (isValidPage && canMoveBack)
                first.Click += new EventHandler(first_Click);
            first.Font.Name = "webdings";
            first.Font.Size = FontUnit.Medium;
            first.ForeColor = ForeColor;
            first.ToolTip = "第一页";
            first.Text = "7";
            first.Enabled = isValidPage && canMoveBack;
            if (!(first.Enabled))
                first.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(first);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            // 呈现 << 按钮
            LinkButton prev = new LinkButton();
            prev.ID = "Prev";
            if (isValidPage && canMoveBack)
                prev.Click += new EventHandler(prev_Click);
            prev.Font.Name = "webdings";
            prev.Font.Size = FontUnit.Medium;
            prev.ForeColor = ForeColor;
            prev.ToolTip = "上一页";
            prev.Text = "3";
            prev.Enabled = isValidPage && canMoveBack;
            if (!(prev.Enabled))
                prev.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(prev);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            // 呈现 > 按钮
            LinkButton next = new LinkButton();
            next.ID = "Next";
            if (isValidPage && canMoveForward)
                next.Click += new EventHandler(next_Click);
            next.Font.Name = "webdings";
            next.Font.Size = FontUnit.Medium;
            next.ForeColor = ForeColor;
            next.ToolTip = "下一页";
            next.Text = "4";
            next.Enabled = isValidPage && canMoveForward;
            if (!(next.Enabled))
                next.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(next);

            // 添加一个空格
            cell.Controls.Add(new LiteralControl("&nbsp;"));

            // 呈现 >> 按钮
            LinkButton last = new LinkButton();
            last.ID = "Last";
            if (isValidPage && canMoveForward)
                last.Click += new EventHandler(last_Click);
            last.Font.Name = "webdings";
            last.Font.Size = FontUnit.Medium;
            last.ForeColor = ForeColor;
            last.ToolTip = "最后一页";
            last.Text = "8";
            last.Enabled = isValidPage && canMoveForward;
            if (!(last.Enabled))
                last.Style.Add("color", "#A0A0A0");
            cell.Controls.Add(last);
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 创建下拉框页码显示
        /// </summary>
        /// <param name="cell">列对象</param>
        private void BuildNumericPagesUI(TableCell cell)
        {
            // 呈现一个下拉框列表
            DropDownList pageList = new DropDownList();
            pageList.ID = "PageList";
            pageList.AutoPostBack = true;
            pageList.SelectedIndexChanged += new EventHandler(PageList_Click);
            pageList.Font.Name = Font.Name;
            pageList.Font.Size = Font.Size;
            pageList.ForeColor = ForeColor;

            // 当无分页数据时，设置一个默认值
            if (TotalPages <= 0 || CurrentPageIndex == -1)
            {
                pageList.Items.Add("无分页");
                pageList.Enabled = false;
                pageList.SelectedIndex = 0;
                pageList.Style.Add("color", "#A0A0A0");
            }
            else // 移动列表
            {
                for (int i = 1; i <= TotalPages; i++)
                {
                    ListItem item = new ListItem(i.ToString(), i.ToString());
                    pageList.Items.Add(item);
                }
                pageList.SelectedIndex = CurrentPageIndex - 1;
            }
            cell.Controls.Add(pageList);
        }

        #endregion

        #region 创建数字页码按钮

        /// <summary>
        /// 创建数字页码显示
        /// </summary>
        private void BuildNumPageUIWithPagerCSS(TableCell cell)
        {
            StringBuilder PageText = new StringBuilder();
            string SqlPagerCopyright = @"<!------------------------------------------
	深圳博客技术论坛：http://bbs.szblogs.com
 ------------------------------------------------------------------>";
            StringBuilder Pager_LinkButton_Left = new StringBuilder();
            StringBuilder Pager_LinkButton_Right = new StringBuilder();

            //==============上一页按钮

            if (this.CurrentPageIndex > 1)
            {
                Pager_LinkButton_Left.Append("<li class='previous'><a href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(1) + ");return false;'>" + this.FirstButton + "</a></li>");
                Pager_LinkButton_Left.Append("<li class='previous'><a  href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(CurrentPageIndex - 1) + ");return false;'>" + this.PrveButton + "</a></li>");
            }
            else
            {
                Pager_LinkButton_Left.Append("<li class='previous-off'>" + this.FirstButton + "</li>");
                Pager_LinkButton_Left.Append("<li class='previous-off'>" + this.PrveButton + "</li>");
            }
            //==============下一页按钮
            if (this.CurrentPageIndex < this.PageCount)
            {
                Pager_LinkButton_Right.Append("<li class='next'><a  href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(CurrentPageIndex + 1) + ");return false;'>" + this.NextButton + "</a></li>");
                Pager_LinkButton_Right.Append("<li class='next'><a  href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(TotalPages) + ");return false;'>" + this.LastButton + "</a></li>");
            }
            else
            {
                Pager_LinkButton_Right.Append("<li class='next-off'>" + this.NextButton + "</li>");
                Pager_LinkButton_Right.Append("<li class='next-off'>" + this.LastButton + "</li>");
            }

            //===========是否可见===================
            if (this.Visible == true)
            {
                string _DescriptionText = "共有" + (PageCount) + "页，当前" + CurrentPageIndex + "页/" + (PageCount);
                PageText.Append("<Div Style=\"display:inline\">");

                PageText.Append("<ul id=" + PaterElementID + ">");
                PageText.Append("<li class=\"pageinfo\">[ " + _DescriptionText + " ]</li>");
                PageText.Append(Pager_LinkButton_Left.ToString());

                StringBuilder Page_Text_Left = new StringBuilder();
                int Page_Text_Num;
                int Page_Text_Start;

                if (PageCount <= (this.LeftPageSize + this.RightPageSize))//===============如果总页数小于两边要显示的页数=====================
                {
                    Page_Text_Start = 1;
                    Page_Text_Num = PageCount;
                }
                else
                {
                    if (this.CurrentPageIndex <= this.LeftPageSize)//===============当前页码小于左边显示记录=====================
                    {
                        Page_Text_Start = 1;
                        Page_Text_Num = this.LeftPageSize + this.RightPageSize;
                    }
                    else//===============当前页码大于等于右边显示记录=====================
                    {
                        if (this.CurrentPageIndex >= PageCount - this.RightPageSize)
                        {
                            Page_Text_Start = this.CurrentPageIndex - this.LeftPageSize;
                            Page_Text_Num = PageCount;
                        }
                        else
                        {
                            Page_Text_Start = this.CurrentPageIndex - this.LeftPageSize;
                            Page_Text_Num = this.CurrentPageIndex + this.RightPageSize;
                        }
                    }
                }

                for (int i = Page_Text_Start; i <= Page_Text_Num; i++)
                {
                    if (this.CurrentPageIndex == i)
                    {
                        Page_Text_Left.Append("<li class=\"active\">");
                        Page_Text_Left.Append("<a href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(i) + ");return false;' >" + i + "</a>");
                        Page_Text_Left.Append("</li>");
                    }
                    else
                    {
                        Page_Text_Left.Append("<li>");
                        Page_Text_Left.Append("<a href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(i) + ");return false;' >" + i + "</a>");
                        Page_Text_Left.Append("</li>");
                    }
                }
                PageText.Append(Page_Text_Left.ToString());
                PageText.Append(Pager_LinkButton_Right.ToString());
                if (ButtonAndTextBoxVisible == true)
                {
                    PageText.Append("<li>");
                    PageText.Append("<input id=\"" + this.UniqueID + "_PageNo\" type=\"text\" onkeyup=\"value=value.replace(/[^\\d]/g,'') \"  onbeforepaste=\"clipboardData.setData('text',clipboardData.getData('text').replace(/[^\\d]/g,''))\"  name=\"" + this.UniqueID + "_PageNo\" value=\"" + this.CurrentPageIndex + "\" size=\"" + TextBoxWidth + "\"  class=\"buttoninfo\"/>");

                    PageText.Append("&nbsp;&nbsp;<input id=\"" + this.UniqueID + "_goto\" onclick=\"" + this.UniqueID + "_CheckPage(" + CurrentPageIndex + ");" + ClientSetPager + "('" + PaternalID + "',document.getElementById('" + this.UniqueID + "_PageNo').value);return false;\" type=\"button\" value=\"" + ButtonText + "\" class=\"buttoninfo\"/>");
                    PageText.Append("</li>");
                    PageText.Append(WriteJs());
                }
                PageText.Append("</ul></div>");
                PageText.Append(SqlPagerCopyright);
                Literal pageLiter = new Literal();
                pageLiter.Text = PageText.ToString();
                cell.Controls.Add(pageLiter);
            }
        }

        /// <summary>
        /// 创建数字页码显示
        /// </summary>
        private void BuildNumPageUI(TableCell cell)
        {
            string Page_Text = @"<!------------------------------------------
	深圳博客技术论坛：http://bbs.szblogs.com
 ------------------------------------------------------------------>";

            if (this.LinkTextType == LinkTextType.Image)
            {
                FirstButton = "<img src=" + FirstButton + " border='0'>";
                PrveButton = "<img src=" + PrveButton + " border='0'>";
                NextButton = "<img src=" + NextButton + " border='0'>";
                LastButton = "<img src=" + LastButton + " border='0'>";
            }

            string Pager_LinkButton_Left = "";
            string Pager_LinkButton_Right = "";
            //==============上一页按钮

            if (this.CurrentPageIndex > 1)
            {
                Pager_LinkButton_Left = "<a href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(1) + ");return false;'>" + this.FirstButton + "</a>";
                Pager_LinkButton_Left += "&nbsp;<a class=\"" + LinkTextCssClass + "\" href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(CurrentPageIndex - 1) + ");return false;'>" + this.PrveButton + "</a>";
            }
            else
            {
                Pager_LinkButton_Left += "&nbsp;" + this.FirstButton + "";
                Pager_LinkButton_Left += "&nbsp;" + this.PrveButton + "";
            }
            //==============下一页按钮
            if (this.CurrentPageIndex < this.PageCount)
            {
                Pager_LinkButton_Right = "<a class=\"" + LinkTextCssClass + "\" href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(CurrentPageIndex + 1) + ");return false;'>" + this.NextButton + "</a>";
                Pager_LinkButton_Right += "&nbsp;<a class=\"" + LinkTextCssClass + "\" href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(TotalPages) + ");return false;'>" + this.LastButton + "</a>";
            }
            else
            {
                Pager_LinkButton_Right = "" + this.NextButton + "";
                Pager_LinkButton_Right += "" + this.LastButton + "";
            }
            string FontCollection = "";
            FontCollection += "font:'" + this.Font.Names + "';";
            FontCollection += "font-size:" + this.Font.Size + ";";
            if (this.Font.Italic == true)
            {
                FontCollection += "font-style: italic;";
            }
            if (this.Font.Bold == true)
            {
                FontCollection += "font-weight: bold;";
            }
            FontCollection += "text-decoration:";
            if (this.Font.Overline == true)
            {
                FontCollection += " overline ";
            }
            if (this.Font.Underline == true)
            {
                FontCollection += " underline ";
            }
            if (this.Font.Strikeout == true)
            {
                FontCollection += " line-through ";
            }
            FontCollection += ";";
            FontCollection += "";
            FontCollection += "";
            FontCollection += "";

            //===========是否可见===================
            if (this.Visible == true)
            {
                string _DescriptionText = "共有" + (PageCount) + "页，当前" + CurrentPageIndex + "页/" + (PageCount);
                Page_Text += "<table align=" + Align.ToString() + " style=\"" + FontCollection + "\" title=\"" + this.ToolTip + "\" cellspacing=\"" + this.CellSpacing + "\" cellpadding=\"" + this.CellPadding + "\" ID=\"Table_" + base.UniqueID + "\" height=\"" + this.Height + "\" width=\"" + this.Width + "\" class=\"" + this.CssClass + "\" border=\"" + this.BorderWidth + "\"  bgcolor=\"" + ColorTranslator.ToHtml(BackColor).ToString() + "\" bordercolor=\"" + ColorTranslator.ToHtml(BorderColor) + "\"><tr>\t\n";
                if (_DescriptionText != "")
                    Page_Text += "<td nowrap=\"true\"  align=\"center\" bordercolor=\"\" style = ''  bgcolor=\"\">" + _DescriptionText + "</td>\t\n";
                Page_Text += "<td nowrap=\"true\"  align=\"center\" bordercolor=\"\"   bgcolor=\"\">&nbsp;" + Pager_LinkButton_Left + "&nbsp;</td>\t\n";

                string Page_Text_Left = "";
                int Page_Text_Num;
                int Page_Text_Start;

                if (PageCount <= (this.LeftPageSize + this.RightPageSize))//===============如果总页数小于两边要显示的页数=====================
                {
                    Page_Text_Start = 1;
                    Page_Text_Num = PageCount;
                }
                else
                {
                    if (this.CurrentPageIndex <= this.LeftPageSize)//===============当前页码小于左边显示记录=====================
                    {
                        Page_Text_Start = 1;
                        Page_Text_Num = this.LeftPageSize + this.RightPageSize;
                    }
                    else//===============当前页码大于等于右边显示记录=====================
                    {
                        if (this.CurrentPageIndex >= PageCount - this.RightPageSize)
                        {
                            Page_Text_Start = this.CurrentPageIndex - this.LeftPageSize;
                            Page_Text_Num = PageCount;
                        }
                        else
                        {
                            Page_Text_Start = this.CurrentPageIndex - this.LeftPageSize;
                            Page_Text_Num = this.CurrentPageIndex + this.RightPageSize;
                        }
                    }
                }

                for (int i = Page_Text_Start; i <= Page_Text_Num; i++)
                {
                    if (this.CurrentPageIndex == i)
                    {
                        Page_Text_Left += "<td  nowrap=\"true\"  style=\"width:" + this.LinkNumberWidth + ";height:" + this.LinkNumberHeight + ";\" align=\"center\"  ><a href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(i) + ");return false;' class='" + this.LinkNumberCssClass + "'><b><font color=\"" + ColorTranslator.ToHtml(this.CurrentNumberColor) + "\">" + i + "</font></b></a></td>\t\n";
                    }
                    else
                    {
                        Page_Text_Left += "<td  nowrap=\"true\"  style=\"width:" + this.LinkNumberWidth + ";height:" + this.LinkNumberHeight + ";\" align=\"center\" bgcolor=\"\"><a href='#' onclick='" + ClientSetPager + "(\"" + PaternalID + "\"," + Convert.ToString(i) + ");return false;' class='" + this.LinkNumberCssClass + "'>" + i + "</a></td>\t\n";
                    }
                }
                Page_Text += Page_Text_Left;


                Page_Text += "<td  align=\"center\" nowrap=\"true\" bordercolor=\"\"  bgcolor=\"\">&nbsp;" + Pager_LinkButton_Right + "&nbsp;</td>\t\n";
                if (ButtonAndTextBoxVisible == true)
                {

                    Page_Text += "<td  align=\"center\" nowrap=\"true\" bordercolor=\"\"  bgcolor=\"\"><input id=\"" + this.UniqueID + "_PageNo\" type=\"text\" onkeyup=\"value=value.replace(/[^\\d]/g,'') \"  onbeforepaste=\"clipboardData.setData('text',clipboardData.getData('text').replace(/[^\\d]/g,''))\"  name=\"" + this.UniqueID + "_PageNo\" value=\"" + this.CurrentPageIndex + "\" size=\"" + TextBoxWidth + "\"/>";
                    if (this.ButtonType == ButtonType.Button)
                    {
                        Page_Text += "<input id=\"" + this.UniqueID + "_goto\" onclick=\"" + this.UniqueID + "_CheckPage(" + CurrentPageIndex + ");" + ClientSetPager + "('" + PaternalID + "',document.getElementById('" + this.UniqueID + "_PageNo').value);return false;\" type=\"button\" value=\"" + ButtonText + "\" />";
                    }
                    else
                    {
                        Page_Text += "<input id=\"" + this.UniqueID + "_goto\" onclick='" + this.UniqueID + "_CheckPage(" + CurrentPageIndex + ");" + ClientSetPager + "('" + PaternalID + "',document.getElementById('" + this.UniqueID + "_PageNo'));return false;' type=\"image\" value=\"" + ButtonText + "\" src=\"" + ButtonText + "\" />";
                    }
                    Page_Text += "</td>\t\n";
                    Page_Text += WriteJs();
                }
                Page_Text += "</tr></table>\t\n";
                Literal pageLiter = new Literal();
                pageLiter.Text = Page_Text;
                cell.Controls.Add(pageLiter);
            }
        }

        private string WriteJs()
        {
            string HTML = "";
            HTML += "<script language =javascript>\n";
            HTML += "function " + this.UniqueID + "_CheckPage(page)\n";
            HTML += "{\n";
            HTML += "   var b = document.getElementById(\"" + this.UniqueID + "_PageNo\").value;\n";
            HTML += "   if(b == 0 || b>" + (this.PageCount) + "){\n";
            HTML += "      alert(\"无效页数！\");\n";
            HTML += "      document.getElementById(\"" + this.UniqueID + "_PageNo\").value=\"\";\n";
            HTML += "      document.getElementById(\"" + this.UniqueID + "_PageNo\").focus();\n";
            HTML += "      \n}";
            HTML += "}\n";
            HTML += "function " + this.UniqueID + "_SubmitKeyClick(button)\n";
            HTML += "{ \n";
            HTML += "   if (event.keyCode == 13) \n";
            HTML += "   {\n";
            HTML += "       event.keyCode=9;\n";
            HTML += "       event.returnValue = false;\n";
            HTML += "       document.all[button].click();\n";
            HTML += "   }\n";
            HTML += "}\n";
            HTML += "</script>";
            return HTML;
        }

        #endregion
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 创建当前页面显示的页码文本
        /// </summary>
        /// <param name="cell">列对象</param>
        private void BuildCurrentPage(TableCell cell)
        {

            // 显示文本的模板：第X页/总Y页
            if (CurrentPageIndex < 0 || CurrentPageIndex > TotalPages)
                cell.Text = NoPageSelectedText;
            else
            {
                switch (ShowCount)
                {
                    case 0:
                        CurrentPageText = "第{0}页/总{1}页 ";
                        cell.Text = String.Format(CurrentPageText, (CurrentPageIndex), TotalPages);
                        break;
                    case 1:
                        CurrentPageText = "第{0}页/总{1}页 [每页{2}条/共{3}条记录]";
                        cell.Text = String.Format(CurrentPageText, (CurrentPageIndex), TotalPages, ItemsPerPage, _totalCount);
                        break;
                    default:
                        CurrentPageText = "";
                        cell.Text = "";
                        break;

                }
            }
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 确保当前页面索引为有效的（0,总页数或者-1）
        /// </summary>
        private void ValidatePageIndex()
        {
            if (!(CurrentPageIndex >= 1 && CurrentPageIndex <= TotalPages))
                CurrentPageIndex = -1;
            return;
        }
        // ***********************************************************************        

        // ***********************************************************************
        /// <summary>
        /// 一次性获取所有数据进行分页，使用了cache
        /// </summary>
        private void FetchAllData()
        {
            // 在缓存里查找数据
            DataTable data;
            string strSQL = string.Empty;
            data = (DataTable)CacheHelper.Get(CacheKeyName);
            strSQL = (string)CacheHelper.Get("SelectCommand");

            //检测如果查询条件改变了,则重新查询,同时也保证了缓存的使用
            if (data == null || strSQL != SelectCommand || data.Rows.Count != _customDataSource.Tables[0].Rows.Count)
            {
                // 使用排序信息填充
                AdjustSelectCommand();

                // 如果缓存过期或者无数据，即从数据库取得
                data = new DataTable();
                if (!UseCustomDataSource)
                    data = DBManage.ExecuteDataset(SelectCommand, "ds").Tables[0];
                else
                    data = _customDataSource.Tables[0];

                CacheHelper.Insert(CacheKeyName, data, CacheDuration);
                CacheHelper.Insert("SelectCommand", SelectCommand, CacheDuration);
            }

            // 为分页控件配置分页数据源
            if (_dataSource == null)
                _dataSource = new PagedDataSource();
            _dataSource.DataSource = data.DefaultView; // must be IEnumerable!
            _dataSource.AllowPaging = true;
            _dataSource.PageSize = ItemsPerPage;
            TotalPages = _dataSource.PageCount;
            _totalCount = data.DefaultView.Count;

            // 确保页索引是有效的
            ValidatePageIndex();
            if (CurrentPageIndex == -1)
            {
                _dataSource = null;
                return;
            }

            // 选择当前页面
            _dataSource.CurrentPageIndex = CurrentPageIndex - 1;
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 处理排序关键字
        /// </summary>
        private void AdjustSelectCommand()
        {
            // 如果有 ORDER BY 排序则进行截取
            string temp = SelectCommand.ToLower();
            int pos = temp.IndexOf("order by");
            if (pos > -1)
                SelectCommand = SelectCommand.Substring(0, pos);

            // 如果指定了排序关键字，则添加一个排序信息
            string sortstyle = "ASC";
            if (SortStyle == SortStyle.DESC)
                sortstyle = "DESC";
            if (SortField != "")
                SelectCommand += " ORDER BY " + SortField + " " + sortstyle;
        }
        // ***********************************************************************
        /// <summary>
        /// 跳转到指定页
        /// </summary>
        /// <param name="pageIndex">页面索引</param>
        public void GoToPage(int pageIndex)
        {
            // 准备事件数据
            PageChangedEventArgs e = new PageChangedEventArgs();
            e.OldPageIndex = CurrentPageIndex;
            e.NewPageIndex = pageIndex;

            // 更新当前页面索引
            CurrentPageIndex = pageIndex;

            // 第一页改变时的事件
            OnPageIndexChanged(e);

            // 绑定新数据
            DataBind();
        }
        // ***********************************************************************

        #region 按钮点击事件
        // ***********************************************************************        
        /// <summary>
        /// 第一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void first_Click(object sender, EventArgs e)
        {
            GoToPage(1);
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 上一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void prev_Click(object sender, EventArgs e)
        {
            GoToPage(CurrentPageIndex - 1);
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 下一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void next_Click(object sender, EventArgs e)
        {
            GoToPage(CurrentPageIndex + 1);
        }
        // ***********************************************************************

        // ***********************************************************************
        /// <summary>
        /// 最后一页按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void last_Click(object sender, EventArgs e)
        {
            GoToPage(TotalPages);
        }
        // ***********************************************************************
        /// <summary>
        /// 下拉框选择事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PageList_Click(object sender, EventArgs e)
        {
            DropDownList pageList = (DropDownList)sender;
            int pageIndex = Convert.ToInt32(pageList.SelectedItem.Value);
            GoToPage(pageIndex);
        }
        // ***********************************************************************
        #endregion

        #endregion
    }
    #endregion
}
