ASP.NET 2.0 — DataList分頁

來源:互聯網
上載者:User
DataList分頁

首先說明下:並非全部本人原創,大部分參考了別人的代碼,我只是修正了一點bug而已。
--------------------------------------------------------------------------------------------------------
前台代碼:
------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="News_test" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>無標題頁</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <TABLE id="Table1" style="Z-INDEX: 101; LEFT: 32px; WIDTH: 752px; POSITION: absolute; TOP: 16px; HEIGHT: 312px" cellSpacing="0" cellPadding="0" width="752" border="0">
            <TR>
                <TD style="HEIGHT: 29px"><FONT face="宋體">DataList分頁技術和超級連結</FONT></TD>
            </TR>
            <TR>
                <TD style="HEIGHT: 252px">
                <asp:datalist id="DataList1" runat="server" Width="576px" Height="96px">
                     <HeaderTemplate>
                            定單編號<td>
                            員工編號<td>
                            定單日期<td>
                            運費<td>
                            運往所在城市
                     </HeaderTemplate>

                     <ItemTemplate>
                        <%# DataBinder.Eval(Container.DataItem,"OrderID")%> <td>
                        <%# DataBinder.Eval(Container.DataItem,"CustomerID")%> <td>
                        <%# DataBinder.Eval(Container.DataItem,"OrderDate")%> <td>
                        <%# DataBinder.Eval(Container.DataItem,"Freight")%>  <td>
                        <%# DataBinder.Eval(Container.DataItem,"ShipCity")%>
                     </ItemTemplate>
                 </asp:datalist>
                 </TD>
                </TR>
                <TR>
                    <TD><FONT face="宋體">

            <asp:linkbutton id="FirstLB" runat="server" OnCommand="LinkButton_Click" CommandName="first">第一頁</asp:linkbutton>&nbsp;
            <asp:linkbutton id="PreviousLB" runat="server" OnCommand="LinkButton_Click" CommandName="prev">上一頁</asp:linkbutton>&nbsp;
            <asp:linkbutton id="NextLB" runat="server" OnCommand=LinkButton_Click CommandName="next">下一頁</asp:linkbutton>&nbsp;
            <asp:linkbutton id="EndLB" runat="server" OnCommand=LinkButton_Click CommandName="end">最後一頁</asp:linkbutton>&nbsp;&nbsp;
            總<asp:label id="TotalLbl" runat="server"></asp:label>頁 當前第<asp:label id="CurrentLbl" runat="server"></asp:label>頁
            <asp:linkbutton id="JumpLB" runat="server" OnCommand=LinkButton_Click CommandName="jump">跳到</asp:linkbutton>第
            <asp:textbox id="TextBox1" runat="server" Width="90px"></asp:textbox>
            頁</FONT></TD>
            </TR>
            </TABLE>
    </div>
    </form>
</body>
</html>
-------------------------------------------------
後台代碼:
----------
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;

public partial class News_test : System.Web.UI.Page
{
    int CurrentPage;//當前頁數
    int PageSize;   //每頁條數
    int PageCount;  //總頁數
    int RecordCount;//總條數
    private void Page_Load(object sender, System.EventArgs e)
    {
        // 在此處放置使用者代碼以初始化頁面

        PageSize = 10;//每頁10條記錄
       

        if (!Page.IsPostBack)
        {            
             CurrentPage = 0;//當前頁習慣設為0
            ViewState["PageIndex"] = 0;//頁索引也設為0

            //計算總共有多少記錄
            RecordCount = CalculateRecord();

            //計算總共有多少頁
            if (RecordCount % PageSize == 0)
            {
                PageCount = RecordCount / PageSize;
            }
            else
            {
                PageCount = RecordCount / PageSize + 1;
            } 

            this.TotalLbl.Text = PageCount.ToString();//顯示總頁數
            ViewState["PageCount"] = PageCount;//會話session 對整個 application 有效 ,而檢視狀態 viewstate相當於某個頁面的 session

            this.DataListBind();//不可以放在初始化條件之前就綁定,那樣的話,如果僅有一頁的資料,“下一頁”頁仍然顯示
            
        }

    }

    //計算總共有多少條記錄
    private int CalculateRecord()
    {
        try
        {
            int recordCount;
            SqlConnection con = new SqlConnection("server=127.0.0.1;database=Northwind;uid=sa;pwd=sa");//資料庫使用Northwind;
            con.Open();

            string sql = "select count(*) as count from Orders";
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataReader sdr = cmd.ExecuteReader();

            if (sdr.Read())
            {
                recordCount = Int32.Parse(sdr["count"].ToString());               
            }

            else
            {
                recordCount = 0;
            }

            sdr.Close();
            con.Close();
            return recordCount;
        }

        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    //將資料繫結到Datalist控制項
    public void DataListBind()
    {
        try
        {
            int StartIndex = CurrentPage * PageSize;//設定匯入的起終地址
            string sql = "select * from Orders";
            DataSet ds = new DataSet();
            SqlConnection con = new SqlConnection("server=127.0.0.1;database=Northwind;uid=sa;pwd=sa");
            con.Open();

            SqlDataAdapter sda = new SqlDataAdapter(sql, con);
            sda.Fill(ds, StartIndex, PageSize, "orders");//這是sda.Fill方法的第一次重載,裡面的變數分別是資料集DataSet ,開始記錄數StartRecord,最大的記錄數MaxRecord,資料表名TableName
            this.DataList1.DataSource = ds.Tables["orders"].DefaultView;
            this.DataList1.DataBind();
            this.PreviousLB.Enabled = true;
            this.NextLB.Enabled = true;
            if (CurrentPage == (PageCount - 1)) this.NextLB.Enabled = false;//當為最後一頁時,下一頁連結按鈕不可用
            if (CurrentPage == 0) this.PreviousLB.Enabled = false;//當為第一頁時,上一頁按鈕不可用
            this.CurrentLbl.Text = (CurrentPage + 1).ToString();//當前頁數

        }

        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

  

    public void LinkButton_Click(Object sender, CommandEventArgs e)//自己編寫的按鈕點擊事件
    {
        CurrentPage = (int)ViewState["PageIndex"];//獲得當前頁索引
        PageCount = (int)ViewState["PageCount"];//獲得總頁數

        string cmd = e.CommandName;

        //判斷cmd,以判定翻頁方向

        switch (cmd)
        {
            case "prev"://上一頁
                if (CurrentPage > 0) CurrentPage--;
                break;

            case "next":
                if (CurrentPage < (PageCount - 1)) CurrentPage++;//下一頁
                break;

            case "first"://第一頁
                CurrentPage = 0;
                break;

            case "end"://最後一頁
                CurrentPage = PageCount - 1;
                break;

            case "jump"://跳轉到第幾頁
                if (this.TextBox1.Text.Trim() == "" || Int32.Parse(this.TextBox1.Text.Trim()) > PageCount)//如果輸入數字為空白或超出範圍則返回
                {
                    return;
                }
                else
                {                   
                    CurrentPage = Int32.Parse(this.TextBox1.Text.ToString()) - 1;
                    break;
                }
        }
        ViewState["PageIndex"] = CurrentPage;//獲得當前頁

        this.DataListBind();//重新將DataList綁定到資料庫

    }

}

------------------------
實際使用的時候,要對“跳轉”到的文字框輸入值進行正整數的驗證。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.