如何将DataPager与数据库页面一起使用

我正在使用ListView / DataPager。

出于性能原因,我使用ROW_NUMBER(SQl2005)将结果分页到数据库。

在我的C#代码中,一次只有一页。 我怎么能对DataPager说我有更多的行真的在我的列表中呢?

我创建了一个创建假默认(T)对象的类。 工作得很好:

public class PagedList : IEnumerable, ICollection { private IEnumerable ActualPage { get; set; } private int Total { get; set; } private int StartIndex { get; set; } public PagedList(int total, int startIndex, IEnumerable actualPage) { ActualPage = actualPage; Total = total; StartIndex = startIndex; } public IEnumerator GetEnumerator() { bool passouPagina = false; for (int i = 0; i < Total; i++) { if (i < StartIndex || passouPagina) { yield return default(T); } else { passouPagina = true; foreach (T itempagina in ActualPage) { i++; yield return itempagina; } } } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #region Implementation of ICollection void ICollection.CopyTo(Array array, int index) { throw new NotSupportedException(); } public int Count { get { return Total; } } object ICollection.SyncRoot { get { throw new NotSupportedException(); } } bool ICollection.IsSynchronized { get { throw new NotSupportedException(); } } #endregion } 

用法示例:

 int totalRows = DB.GetTotalPeople(); int rowIndex = (currentPage-1)*pageSize; List peoplePage = DB.GetPeopleAtPage(currentPage); listview.DataSource = new PagedList(totalRows, rowIndex, peoplePage) listView.DataBind(); 

显然我不能评论由Fujiy提供的上述解决方案,但是我发现了以下错误:

GetEnumerator()内部,else分支中的增量将始终使集合跳过一个默认元素,除非您位于PagedList的最后一页。

例如,如果要创建一个包含5个元素的分页列表,则每页包含startindex 3和1个元素。 这可能会进入元素2的else分支。它会将i增加到3,然后返回到for-header,它将增加到4,而不会为i == 3创建默认元素。

  • i == 1 – >默认
  • i == 2 – >默认
  • i == 3 – >实际元素
  • 我== 4 – >跳过
  • 我== 5 – >默认

一个简单的解决方案是使用3个for循环(一个用于ActualPage之前的默认值,一个用于ActualPage,一个用于ActualPage之后的元素)。 或者在Else-branch内部的For-loop之后添加一个i–。