ASP.Net:DataPager Control总是落后于分页

时间:2009-07-15 09:48:10

标签: c# asp.net listview datapager

采用以下示例...包含ListViewDataPager的页面用于分页ListView的数据:

代码背后:

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

来源:

<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>

DataPager的问题在于它始终是绑定的后盾。

例如,当页面加载它在页码1上时。然后当您单击第3页时,它在回发后保留在第1页。然后你点击第5页,在回发后它在第3页找到自己...然后你点击第6页,它在第5页找到自己......依此类推。依此类推。

为什么分页不按预期工作?

6 个答案:

答案 0 :(得分:33)

解决方案

问题是由于Page_Load事件发生了绑定。

为了使其按预期工作,绑定需要在DataPager的{​​{1}}事件中进行,而不是在OnPreRender

来源:

Page_Load

代码背后:

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

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

答案 1 :(得分:6)

我遇到了同样的问题,但每次在datapager prerender上绑定都不是我的选择。相反,我只能在发生分页时通过绑定完成同样的事情。该解决方案可用作Andreas的预渲染解决方案的替代方案。以下对我有用:

通过附加到ListView的PagePropertiesChanged事件,我能够纠正分页问题,​​而无需绑定数据分页器的每个预呈现器。

注意:大多数数据分页器属性都是在外观文件中设置的,这就是它们不在标记中的原因。

标记:

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

代码背后:

protected void Page_Load(object sender, EventArgs e) {
   MyList.PagePropertiesChanged += new EventHandler(MyList_PagePropertiesChanged);
}

/// <summary>
/// Handles the situation where the page properties have changed.  Rebind the data
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void MyList_PagePropertiesChanged(object sender, EventArgs e) {
   MyList.DataSource = GetSomeList();
   MyList.DataBind();
}

答案 2 :(得分:1)

您在数据传输器上缺少OnPreRender事件!

答案 3 :(得分:0)

以下作品非常适合我。

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles   Me.Load
Dim ds As DataSet
ds = SQLHELPER.ExecuteDataSet(CommandType.StoredProcedure, "sp_Locations")
rs.EnableViewState = False
rs.DataSource = ds
rs.DataBind()
End Sub

Protected Sub rs_PagePropertiesChanging(ByVal sender As Object, ByVal e As    PagePropertiesChangingEventArgs)
'set current page startindex, max rows and rebind to false
Pager.SetPageProperties(e.StartRowIndex, e.MaximumRows, False)
'rebind List View
rs.DataBind()
End Sub

<asp:ListView ID="rs" runat="server" onpagepropertieschanging="rs_PagePropertiesChanging">

答案 4 :(得分:0)

或者,如果您要构建仅包含ListView的用户控件,则只需将寻呼机事件处理程序指向Page_Load方法,因为Page_Load方法不是运行其他任何东西:

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

答案 5 :(得分:-2)

在页面加载中你应该把代码放在之间 if(!IsPostBack) { }

它将解决您的问题。