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

以下示例为例:一个带有ListViewDataPager的页面,用于分页ListView的数据:

代码背后:

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

资源:

         

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

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

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

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

为了使其按预期工作, 绑定需要在DataPagerOnPreRender事件中发生 ,而不是在Page_Load

资源:

      

代码背后:

 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(); } 

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

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

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

标记:

   <% //LayoutTemplate and ItemTemplate removed for the example %>  

代码背后:

 protected void Page_Load(object sender, EventArgs e) { MyList.PagePropertiesChanged += new EventHandler(MyList_PagePropertiesChanged); } ///  /// Handles the situation where the page properties have changed. Rebind the data ///  ///  ///  private void MyList_PagePropertiesChanged(object sender, EventArgs e) { MyList.DataSource = GetSomeList(); MyList.DataBind(); } 

您错过了数据传输器上的OnPreRender事件!

以下作品对我来说很完美。

 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  

或者,如果要构建仅包含ListView的User控件 ,则只需将pager事件处理程序指向Page_Load方法,因为Page_Load方法未运行任何其他方法:

  

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

它会解决你的问题。