戰地連結︰ Home My Flickr NBA.com About

2008年10月28日星期二

Adding Paging Support to the "Repeater"

Overview

Repeater is very useful in displaying data with a fully customized layout. However, repeater does not have built-in paging support. I found an article in "4GuysFromRolla" by "Harrison Enholm", talking about how to add paging support to the Repeater or DataList, with the use of "PagedDataSource" Class.

Reference

Adding Paging Support to the Repeater or DataList with the PagedDataSource Class

Steps

  1. Add a Repeater to the aspx page:

    <asp:Repeater ID="RprChild" runat="server" OnItemDataBound="RprChild_DataBound">

         <ItemTemplate>

              <%# DataBinder.Eval(Container.DataItem, "FirstName") %>

         </ItemTemplate>

    </asp:Repeater>

  2. Setup a property to stored the "Current Page" variable of the Repeater in ViewState:

    public int CurrentPage

            {

                get

                {

                    // look for current page in ViewState

                    object o = this.ViewState["_CurrentPage"];

                    if (o == null)

                        return 0;    // By default shows the first page

                    else

                        return (int)o;

                }

                set

                {

                    this.ViewState["_CurrentPage"] = value;

                }

            }

  3. Declare a method "ItemsGet()" to assign a list of objects to the "PagedDataSource" objPds, and bind it with the Repeater:

    protected void ItemsGet(List<Profile> children)

            {

                // Populate the repeater control with the Items DataSet

                PagedDataSource objPds = new PagedDataSource();

                objPds.DataSource = children;

                objPds.AllowPaging = true;

                objPds.PageSize = 6;

     

                objPds.CurrentPageIndex = CurrentPage;

     

                // Disable Prev or Next buttons if necessary

                LkbPrevPage.Enabled = !objPds.IsFirstPage;

                LkbNextPage.Enabled = !objPds.IsLastPage;

     

                RprChild.DataSource = objPds;

                RprChild.DataBind();

            }

  4. Add a "Previous Page" & a "Next page" button, with their OnClick Event like these:

    protected void LkbPrevPage_OnClick(object sender, EventArgs e)

            {

                CurrentPage -= 1;

                ItemsGet(member.Children);

            }

     

    protected void LkbNextPage_OnClick(object sender, EventArgs e)

            {

                CurrentPage += 1;

                ItemsGet(member.Children);

            }

  5. Done!

沒有留言: