Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
253 views
in Technique[技术] by (71.8m points)

c# - ASP.Net : DataPager Control always a step behind with paging

Take the following example...a page with a ListView and a DataPager used for paging the data of the ListView:

Code Behind:

protected void Page_Load(object sender, EventArgs e)
{
    MyList.DataSource = GetSomeList();
    MyList.DataBind();
}

Source:

<asp:ListView ID="MyList" runat="server">
    <% //LayoutTemplate and ItemTemplate removed for the example %>
</asp:ListView>

<asp:DataPager ID="ListPager" PagedControlID="MyList" runat="server" PageSize="10">
    <Fields>
        <asp:NumericPagerField  />
    </Fields>
</asp:DataPager>

The problem with the DataPager is that it is always a step-behind with the binding.

For example, when the page loads it's on page number 1. Then when you click on page 3, it stays on page 1 after the postback. Then you click on page 5, and after the postback it finds itself on page 3...and after that you click on page 6, and it finds itself on page 5...and so on and so forth.

Why isn't the paging working as expected?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Solution

The problem is due to the binding occuring on the Page_Load event.

For this to work as expected, the binding needs to happen in the DataPager's OnPreRender event, not in the Page_Load.

Source:

<asp:DataPager ID="ListPager" PagedControlID="MyList" runat="server" PageSize="10"
    OnPreRender="ListPager_PreRender">

<Fields>
        <asp:NumericPagerField  />
    </Fields>
</asp:DataPager>

Code Behind:

protected void Page_Load(object sender, EventArgs e)
{
    //Binding code moved from Page_Load
    //to the ListView's PreRender event
}

protected void ListPager_PreRender(object sender, EventArgs e)
{
    MyList.DataSource = GetSomeList();
    MyList.DataBind();    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...