天天看點

如何讓DataList具有分頁的功能(asp.net)

一.前言

使用asp.net 的Gridview控件,你可以友善地進行資料綁定、分頁顯示,模闆能讓資料顯示更加多姿多彩,但是Gridview顯示隻能按記錄一行一行垂直顯示,不能橫排,它更多地用來顯示普通的資料記錄。DataList支援橫向顯示,你所要做的僅僅是把RepeatDirection設成Horizontal,RepeatColumns設定要橫向顯示的列數,當顯示的資訊涉及圖檔等複雜資訊時,這些功能能讓頁面顯示更加美觀和符合頁面要求。但是DataList不支援分頁的功能,當資料量很大時這是令人煩惱的問題。下面的方法告訴你怎麼自己做一個DataList分頁的功能,并且可以友善地進行資料綁定。

二.測試資料

DataList測試資料使用文章《如何讓Gridview在沒有資料的時候顯示表頭》的資料,詳情請檢視

http://blog.csdn.net/zhyuanshan/archive/2007/10/08/1815899.aspx

三.分頁使用者控件編寫

1.頁面設計

使用VS2005建立一個網站,命名為DataListPaging,新增一個使用者控件PagingDataList.ascx,在使用者控件中使用兩個div命名為divDataListBody和divPagingButtons,分别放DataList控件和分頁按鈕。

在divDataListBody中從工具欄放入一個DataList,設定RepeatColumns=”2”、RepeatDirection=”Horizontal”,資料綁定如下所示:

<div runat="server" id="divDataListBody" style="text-align:center;">

    <asp:DataList ID="DataList1" runat="server" RepeatColumns="2" DataKeyField="temple_id" RepeatDirection="Horizontal">

        <ItemTemplate>

            temple_id:

            <asp:Label ID="temple_idLabel" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "temple_id") %>'></asp:Label><br />

            temple_name:

            <asp:Label ID="temple_nameLabel" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "temple_name") %>'>

            </asp:Label><br />

            location:

            <asp:Label ID="locationLabel" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "location") %>'></asp:Label><br />

            build_date:

            <asp:Label ID="build_dateLabel" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "build_date") %>'>

            </asp:Label><br /><br />

        </ItemTemplate>

    </asp:DataList>

    </div>

在divPagingButtons中放入4個LinkButton控件,分别為lbtnFirstPage、lbtnPreviousPage、lbtnNextPage、lbtnLastPage顯示文本分别為“第一頁”、“上一頁”、“下一頁”和“最後一頁”,CommandName屬性分别設為FirstPage、PreviousPage、NextPage、LastPage,每個按鈕重載OnCommand事件,時間處理函數都為"lbtn_Click",如下代碼所示:

<div runat="server" id="divPagingButtons" style ="text-align:center;">

        <asp:LinkButton ID="lbtnFirstPage" runat="server" Font-Underline="False" CommandName="FirstPage" OnCommand="lbtn_Click">第一頁</asp:LinkButton>

        <asp:LinkButton

            ID="lbtnPreviousPage" runat="server" CommandName="PreviousPage" OnCommand="lbtn_Click">上一頁</asp:LinkButton>

        <asp:LinkButton ID="lbtnNextPage"

                runat="server" CommandName="NextPage" OnCommand="lbtn_Click">下一頁</asp:LinkButton>

        <asp:LinkButton ID="lbtnLastPage" runat="server" CommandName="LastPage" OnCommand="lbtn_Click">最後一頁</asp:LinkButton>&nbsp;</div>

2.背景代碼設計

控件模仿asp.net控件資料綁定的方法,首先設計一個公有的事件PageIndexChanging,當點選分頁按鈕時激活。其次有AllowPaging辨別是否允許分頁,如果不允許分頁則顯示所有資料并隐藏分頁按鈕;PageSize辨別每頁顯示的記錄數;PageIndex辨別目前顯示的頁面;DataSource用于設定被綁定資料;調用DataBind()函數進行資料綁定。下面列舉幾個主要的屬性代碼:

1)  分頁事件

public delegate void PagingDelegate(object sender,int NewIndex);

    //分頁事件

public event PagingDelegate PageIndexChanging;

2)AllowPaging屬性

/// <summary>

    /// 擷取或設定是否允許分頁

    /// </summary>

    public bool AllowPaging

    {

        get

        {

            object obj = ViewState["AllowPaging"];

            if (obj == null)

            {

                //預設沒有設定,不允許分頁

                return false;

            }

            return Convert.ToBoolean(obj);

        }

        set

        {

            //儲存屬性

            ViewState["AllowPaging"] = value;

        }

}

3)PageSize屬性

/// <summary>

    /// 擷取或設定顯示頁數

    /// </summary>

    public int PageSize

    {

        get

        {

            object obj = ViewState["PageSize"];

            if (obj == null)

            {

                return 10;

            }

            return Convert.ToInt32(obj);

        }

        set

        {

            ViewState["PageSize"] = value;

        }

    }

4)DataBind()函數設計

/// <summary>

    /// 綁定資料

    /// </summary>

    public override void DataBind()

    {

        DataTable BindTable = null;

        if (_DataSource != null && _DataSource.Rows.Count > 0 && AllowPaging)

        {

            this.TotalRecordCount = _DataSource.Rows.Count;

            int StartRecord, RecordCount;

            //顯示所有按鈕

            SetLinkButtonVisiable(true);

            if (CurrentPage * PageSize < _DataSource.Rows.Count)//記錄起始在正常範圍之内

            {

                StartRecord = CurrentPage * PageSize;

                if (StartRecord + PageSize < _DataSource.Rows.Count)

                {

                    RecordCount = PageSize;

                }

                else//最後一頁

                {

                    SetLinkButton(false);

                    RecordCount = _DataSource.Rows.Count - StartRecord;

                }

            }

            else//記錄起始不在正常範圍之内,CurrentPage設定為很大辨別最後一頁

            {

                this.TotalRecordCount = 0;

                if (_DataSource.Rows.Count - PageSize < 0)//記錄數少于PageSize,既是第一頁也是最後一頁

                {

                    StartRecord = 0;

                }

                else//最後一頁

                {

                    if (_DataSource.Rows.Count % PageSize == 0)//記錄數剛好整除

                    {

                        StartRecord = _DataSource.Rows.Count - PageSize;

                    }

                    else

                    {

                        StartRecord = _DataSource.Rows.Count - (_DataSource.Rows.Count % PageSize);

                    }

                }

                RecordCount = _DataSource.Rows.Count - StartRecord;

                SetLinkButton(false);

            }

            //顯示的是第一頁

            if (StartRecord == 0)

            {

                SetLinkButton(true);

            }

            BindTable = _DataSource.Clone();

            //設定需要顯示的資料

            for (int i = StartRecord; i < RecordCount + StartRecord; i++)

            {

                DataRow row = BindTable.NewRow();

                row.ItemArray = _DataSource.Rows[i].ItemArray;

                BindTable.Rows.Add(row);

            }

        }

        else

        {

            SetLinkButtonVisiable(false);

            BindTable = _DataSource;

        }

        //綁定資料

        this.DataList1.DataSource = BindTable;

        this.DataList1.DataBind();

    }

四.頁面調用使用者控件

控件的使用和asp.net控件的使用非常相似。在Default.aspx頁面中将PagingDataList.ascx頁面拖入其中,前台代碼如下所示:

<div>

        <uc2:PagingDataList id="PagingDataList1" runat="server" PageSize="3" AllowPaging="True" PageIndex="0">

        </uc2:PagingDataList>

    </div>

在此代碼中設定PageSize的大小為3條記錄,預設選中的頁面為第0頁。

在背景服務端代碼中加入從資料庫擷取資料的代碼:

/// <summary>

    /// 從資料庫擷取資料

    /// </summary>

    private void LoadData()

    {

        SqlConnection cn = new SqlConnection("Data Source=BIT-ZHYUANSHAN//SQLEXPRESS;Initial Catalog=test;User ID=sa;Password=123456");

        SqlCommand cmd = new SqlCommand("select *from temple", cn);

        SqlDataAdapter sda = new SqlDataAdapter(cmd);

        DataTable dt = new DataTable();

        sda.Fill(dt);

        this.PagingDataList1.DataSource = dt;

        this.PagingDataList1.DataBind();

    }

在PageLoad事件中調用LoadData(),并且關聯控件的PageIndexChanging事件函數:

protected void Page_Load(object sender, EventArgs e)

    {

        this.PagingDataList1.PageIndexChanging += new PagingDataList.PagingDelegate(PagingDataList1_PageIndexChanging);

        if (!IsPostBack)

        {

            LoadData();

        }

    }

在PageIndexChanging中重新綁定資料:

void PagingDataList1_PageIndexChanging(object sender, int NewIndex)

    {

        LoadData();

 }

五.運作結果

所有工作已經完成,運作網站,可以看見如下圖運作結果:

如何讓DataList具有分頁的功能(asp.net)

在這個頁面顯示中,總記錄隻有五條,是以無法讓所有按鈕顯示出來,頁面沒有加任何style修飾,隻要在頁面中适當加入style頁面美觀就會很好,效果就會比較明顯。

六.源碼

點選以下連結下載下傳源碼:

 CSDN怎麼搞的,檔案上傳怎麼不見了?請使用右鍵下載下傳,下載下傳後把字尾jpg去掉

繼續閱讀