asp.net 分页控件

前台

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Pager.ascx.cs" Inherits="Controls_Core_Pager" %>
<style type="text/css">

    .GridViewPagerStyle {
        background-position: top;
        background-repeat: repeat-x;
        border-bottom: 1px solid #ABC7EC;
        color: #15428B;
        font-weight: bold;
    }

    .GridViewPagerStyle table {
        margin: auto;
        text-align: center;
    }

    .GridViewPagerStyle table td { border: 0px; }

    .GridViewPagerStyle a {
        color: #15428B;
        padding: 0px 1px 0px 1px;
        text-decoration: none;
    }

    .GridViewPagerStyle span {
        color: red;
        font-weight: bold;
        padding: 0px 1px 0px 1px;
        text-decoration: none;
    }
</style>

<script type="text/javascript" language="javascript">
    function checkGo() {
        var txtGoObj = document.getElementById(document.getElementById('hidTextBoxGoClientID').value);

        if (txtGoObj && txtGoObj.value == '') {
            txtGoObj.focus();
            return false;
        }

        return true;
    }
</script>

<center>
    <div style="background-color: #BBD5EC;  100%;">
        <table class="GridViewPagerStyle" cellpadding="1" cellspacing="1" >
            <tr align="center">
                <td valign="middle" runat="server" >
                    <asp:LinkButton ID="imgAll" Text="显示所有" runat="server" OnClick="All_Click" />  |
                </td>
                <td valign="middle" runat="server" >
                    共<asp:Label ID="lblPageCount" runat="server" Text="Label" Style="color: Red;"></asp:Label>页/<asp:Label
                                                                                                                    ID="lblRecordCount" runat="server" Text="Label" Style="color: Red;"></asp:Label>条记录  |
                </td>
                <td valign="middle" runat="server" >
                    当前第<asp:Label ID="lblCurrentPageIndex" runat="server" Text="Label" Style="color: Red;"></asp:Label>页
                </td>
                <td valign="middle">
                    <asp:LinkButton ID="imgFirstPage" runat="server" OnClick="imgFirstPage_Click" Text="首页"></asp:LinkButton>
                </td>
                <td valign="middle">
                    <asp:LinkButton ID="imgPrePage" runat="server" OnClick="imgPrePage_Click" Text="上页"></asp:LinkButton>
                </td>
                <td valign="middle">
                    <asp:LinkButton ID="imgNextPage" runat="server" OnClick="imgNextPage_Click" Text="下页"></asp:LinkButton>
                </td>
                <td valign="middle">
                    <asp:LinkButton ID="imgLastPage" runat="server" OnClick="imgLastPage_Click" Text="尾页"></asp:LinkButton>
                </td>
                <td>
                </td>
                <td valign="middle" runat="server" >
                    转到<asp:TextBox ID="txtGo" runat="server" Width="20px" Height="12" onkeyup="this.value=this.value.replace(/D/g,'')"
                                   onafterpaste="this.value=this.value.replace(/D/g,'')"></asp:TextBox>页
                </td>
                <td valign="middle" runat="server" >
                    <asp:ImageButton ID="imgGo" AlternateText="跳转页面" ImageUrl="../../Images/Go.gif" OnClick="imgGo_Click"
                                     ImageAlign="Middle" runat="server" Height="21px" Width="28px" OnClientClick=" return checkGo(); " />
                </td>
            </tr>
        </table>
    </div>
</center>
<asp:HiddenField ID="hidCurrentPageIndex" runat="server" />
<asp:HiddenField ID="hidPageSize" runat="server" />

 后台:

public partial class Controls_Core_Pager : System.Web.UI.UserControl
{
    public delegate void GridViewDelegate();

    #region Delegate

    public event GridViewDelegate InitLoadData;
    public event GridViewDelegate PageingLoadData;
    public event GridViewDelegate BeforePageing;
    public event GridViewDelegate AfterPageing;

    private const string firstenabledimgurl = "~/Image/pager/first.gif";
    private const string firstdisabledimgurl = "~/image/pager/first_disabled.gif";

    private const string lastenabledimgurl = "~/image/pager/last.gif";
    private const string lastdisabledimgurl = "~/image/pager/last_disabled.gif";

    private const string prevenabledimgurl = "~/image/pager/prev.gif";
    private const string prevdisabledimgurl = "~/image/pager/prev_disabled.gif";

    private const string nextenabledimgurl = "~/image/pager/next.gif";
    private const string nextdisabledimgurl = "~/image/pager/next_disabled.gif";
    #endregion

    public bool SimplePager
    {
        set
        {
            this.tdAll.Visible = !value;
            this.tdCurrentIndex.Visible = !value;
            this.tdImgGo.Visible = !value;
            this.tdPageCount.Visible = !value;
            this.tdTextGo.Visible = !value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public int RecordCount
    {
        get { return (ViewState["RecordCount"] != null) ? (int)ViewState["RecordCount"] : 0; }
        set { ViewState["RecordCount"] = value; }
    }

    public int PageSize
    {
        get
        {
            if (string.IsNullOrEmpty(hidPageSize.Value) ||Convert.ToInt32( hidPageSize.Value)<=0)
                hidPageSize.Value = "20";
            return int.Parse(hidPageSize.Value);
        }
        set
        {
            hidPageSize.Value = value.ToString();
        }
    }

    public int CurrentPageIndex
    {
        get { return (hidCurrentPageIndex.Value == string.Empty) ? 0 : int.Parse(hidCurrentPageIndex.Value); }
        set { hidCurrentPageIndex.Value = value.ToString(); }
    }

    public void LoadData()
    {
        if (InitLoadData != null)
        {
            InitLoadData();
            ShowStatus(0);
        }
    }

    public void ReLoadData()
    {
        if (BeforePageing != null)
        {
            BeforePageing();
        }
        if (PageingLoadData != null)
        {
            PageingLoadData();
            ShowStatus(CurrentPageIndex);
        }
        if (AfterPageing != null)
        {
            AfterPageing();
        }
    }

    private void ShowStatus(int currentPageIndex)
    {
        int pageCount = Convert.ToInt32((RecordCount - 1) / PageSize + 1);
        lblRecordCount.Text = RecordCount.ToString();
        hidCurrentPageIndex.Value = currentPageIndex.ToString();
        if (RecordCount == 0)
        {
            lblPageCount.Text = "0";
            lblCurrentPageIndex.Text = "";
        }
        else
        {
            lblPageCount.Text = pageCount.ToString();
            lblCurrentPageIndex.Text = Convert.ToString(currentPageIndex + 1);
        }

        if (pageCount == 0 || ((currentPageIndex + 1) == 1 && pageCount == 1))
        {
            imgFirstPage.Enabled = false;
            imgPrePage.Enabled = false;
            imgNextPage.Enabled = false;
            imgLastPage.Enabled = false;
        }
        else
        {
            if (currentPageIndex == 0)
            {
                imgPrePage.Enabled = false;
                imgFirstPage.Enabled = false;
                imgNextPage.Enabled = true;
                imgLastPage.Enabled = true;
            }
            else if ((currentPageIndex + 1) == pageCount)
            {
                imgFirstPage.Enabled = true;
                imgPrePage.Enabled = true;
                imgNextPage.Enabled = false;
                imgLastPage.Enabled = false;
            }
            else if (currentPageIndex != 0 && (currentPageIndex + 1) != pageCount)
            {
                imgFirstPage.Enabled = true;
                imgPrePage.Enabled = true;
                imgNextPage.Enabled = true;
                imgLastPage.Enabled = true;
            }
        }
    }

    protected void imgFirstPage_Click(object sender, EventArgs e)
    {
        if (BeforePageing != null)
        {
            BeforePageing();
        }
        if (PageingLoadData != null)
        {
            CurrentPageIndex = 0;
            PageingLoadData();
            ShowStatus(CurrentPageIndex);
        }
        if (AfterPageing != null)
        {
            AfterPageing();
        }
    }

    protected void imgPrePage_Click(object sender, EventArgs e)
    {
        if (BeforePageing != null)
        {
            BeforePageing();
        }
        if (PageingLoadData != null)
        {
            CurrentPageIndex = CurrentPageIndex - 1;
            PageingLoadData();
            ShowStatus(CurrentPageIndex);
        }
        if (AfterPageing != null)
        {
            AfterPageing();
        }
    }

    protected void imgNextPage_Click(object sender, EventArgs e)
    {
        if (BeforePageing != null)
        {
            BeforePageing();
        }
        if (PageingLoadData != null)
        {
            CurrentPageIndex = CurrentPageIndex + 1;
            PageingLoadData();
            ShowStatus(CurrentPageIndex);
        }
        if (AfterPageing != null)
        {
            AfterPageing();
        }
    }

    protected void imgLastPage_Click(object sender, EventArgs e)
    {
        if (BeforePageing != null)
        {
            BeforePageing();
        }
        if (PageingLoadData != null)
        {
            CurrentPageIndex = Convert.ToInt32((RecordCount - 1) / PageSize + 1) - 1;
            PageingLoadData();
            ShowStatus(CurrentPageIndex);
        }
        if (AfterPageing != null)
        {
            AfterPageing();
        }
    }

    public void All_Click(object sender, EventArgs e)
    {
        if (BeforePageing != null)
        {
            BeforePageing();
        }
        if (PageingLoadData != null)
        {
            CurrentPageIndex = 0;
            if (RecordCount > 0)
                PageSize = Convert.ToInt32(RecordCount);
            PageingLoadData();
            ShowStatus(CurrentPageIndex);
        }
        if (AfterPageing != null)
        {
            AfterPageing();
        }
    }

    protected void imgGo_Click(object sender, EventArgs e)
    {
        if (BeforePageing != null)
        {
            BeforePageing();
        }
        if (PageingLoadData != null)
        {
            int pageCount = Convert.ToInt32((RecordCount - 1) / PageSize + 1);
            int goPageIndex= ConvertToInt(this.txtGo.Text.Trim());

            if (pageCount >= goPageIndex)
            {
                CurrentPageIndex = goPageIndex - 1;
                PageingLoadData();
                ShowStatus(CurrentPageIndex);
            }
        }
        if (AfterPageing != null)
        {
            AfterPageing();
        }
    }
    private int ConvertToInt(string p)
    {
        int refvalue = 0;
        try
        {
            refvalue = int.Parse(p);
        }
        catch (Exception)
        {
        }
        return refvalue;
    }
    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        this.Page.ClientScript.RegisterHiddenField("hidTextBoxGoClientID", this.txtGo.ClientID);
    }

}

 测试页面前台代码:

 <div>
            <asp:GridView ID="GridView1" CssClass="GridViewStyle" runat="server" BorderWidth="0px"
                CellPadding="0" AutoGenerateColumns="False" Width="100%" AllowSorting="True"
                EmptyDataText="暂无数据">
                <FooterStyle CssClass="GridViewFooterStyle" />
                <RowStyle CssClass="GridViewRowStyle" BackColor="#F7FAFD" />
                <Columns>
                    <asp:BoundField DataField="ID" HeaderText="ID">
                        <FooterStyle CssClass="hide" />
                        <HeaderStyle CssClass="hide" />
                        <ItemStyle CssClass="hide" />
                    </asp:BoundField>
                    <asp:TemplateField HeaderText="序号">
                        <ItemTemplate>
                           
                            <%#Container.DataItemIndex+1%>
                        </ItemTemplate>
                    </asp:TemplateField>
                    <asp:BoundField HeaderText="ID" DataField="ID" />
                    <asp:BoundField HeaderText="PID" DataField="PID" />
                    <asp:BoundField HeaderText="name" DataField="name" />
                    <asp:BoundField HeaderText="开挖面积" DataField="GROUPNAME" />

           
                </Columns>
      
                <HeaderStyle CssClass="GridViewHeaderStyle" HorizontalAlign="Left" />
                <AlternatingRowStyle BackColor="#EBF4FA" />
            </asp:GridView>
            <div style="text-align: center;">
                <center>
                    <crc:Pager runat="server" ID="uxPager" OnInitLoadData="uxPager_InitLoadData" OnPageingLoadData="uxPager_PageingLoadData" />
                </center>
            </div>
        </div>

测试页面后台代码;

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridProject("select * from student");
        }
      
    }

    private void BindGridProject(string sql)
    {
        ViewState["sql"] = sql;
        this.uxPager.PageSize = Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]);
        this.uxPager.LoadData();

    }
    #region 分页相关
    /// <summary>
    /// 初始化分页控件
    /// </summary>
    protected void uxPager_InitLoadData()
    {
        int totalRecords = -1;
        DataTable table = QueryTable(this.uxPager.CurrentPageIndex, this.uxPager.PageSize, ref totalRecords);
        this.uxPager.RecordCount = totalRecords;
        LoadGridView(table);
    }

    /// <summary>
    /// 加载分页控件
    /// </summary>
    protected void uxPager_PageingLoadData()
    {
        int totalRecord = this.uxPager.RecordCount;
        DataTable table = QueryTable(this.uxPager.CurrentPageIndex, this.uxPager.PageSize, ref totalRecord);
        LoadGridView(table);
    }
    /// <summary>
    /// 获取数据源
    /// </summary>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="totalRecord">总页数</param>
    /// <returns></returns>
    public DataTable QueryTable(int pageIndex, int pageSize, ref int totalRecord)
    {
        OracleDataBase odb = new OracleDataBase("0");
        string sql = ViewState["sql"].ToString();
        totalRecord = odb.GetDataSet(sql).Tables[0].Rows.Count;
        string sqlTableName = sql;
        string selectSql = StructurePagingSql(sqlTableName, pageIndex, pageSize, null);
        return odb.GetDataSet(selectSql).Tables[0];
    }

    /// <summary>
    /// 分页语句
    /// </summary>
    /// <param name="strSQL"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="orderBy">排序</param>
    /// <returns></returns>
    public String StructurePagingSql(string sqlTableName, int pageIndex, int pageSize, string orderBy)
    {
        int startIndex = pageIndex * pageSize;
        int endIndex = startIndex + pageSize;
        StringBuilder selectSql = new StringBuilder();
        selectSql.Append(string.Format(" SELECT *  FROM (SELECT A.*, ROWNUM RN FROM ({0}) A   ", sqlTableName));
        selectSql.Append(string.Format(" WHERE  ROWNUM <= {0} ) WHERE RN > {1} ", endIndex, startIndex));
        return selectSql.ToString();
    }
    private void LoadGridView(DataTable dt)
    {
        this.GridView1.DataSource = dt;
        GridView1.DataBind();
    }
    #endregion