3

I am using the example provided here StackOverflow related question, if i have an even number of items in the grid then it works all good, but if for instance i have an odd number like 7 items, it throws a out of range exception which I fixed by adding this line

public override object GetItemAt(int index)
{
    var offset = ((index % (this._itemsPerPage)) + this.StartIndex) > this._innerList.Count - 1 ? 0 : index % (this._itemsPerPage);
    return this._innerList[this.StartIndex + offset];
}

The problem is that after fixing this, if you set the items per page to 2 then you will have 4 pages, the first 3 pages look right but the last one repeats the last item twice. like this

enter image description here

I am new to WPF and i am not sure how i can handle this piece, i do not understand why it would repeat the item.

Community
  • 1
  • 1
jedgard
  • 868
  • 3
  • 23
  • 41

1 Answers1

7

The issue is not with GetItemAt method, leave it as it was:

    public override object GetItemAt(int index)
    {
        var offset = index % (this._itemsPerPage); 

        return this._innerList[this.StartIndex + offset];
    }

The problem is with Count property override. In case it is the last page it should return the correct items left:

    public override int Count
    {
        get 
        {
            //all pages except the last
            if (CurrentPage < PageCount)
                return this._itemsPerPage;

            //last page
            int remainder = _innerList.Count % this._itemsPerPage;

            return remainder == 0 ? this._itemsPerPage : remainder; 
        }
    }
Novitchi S
  • 3,711
  • 1
  • 31
  • 44
  • 1
    Also if you want to support an empty dataset, you need a check like this at the beginning of that Count override: "if (_innerList.Count == 0) return 0;" – Yushatak Apr 07 '15 at 14:10
  • well i would like to implement sorting @Yushatak. Somehow default sorting of datagrid doesn't work when the itemsource is binded to the paging's collectionview. – wingskush Apr 24 '15 at 06:07
  • Sorting is not working, because the `public override object GetItemAt(int index)` method takes the item from the separately maintained `_internalList`. The base class has the items properly sorted (you can see that during debugging), but the `PagingCollectionView` is not using those items. Unfortunately, the internal list of the base class is not protected, so it's not possible to write a decent child class. I find it odd that WPF doesn't support this out of the box. – Robert F. Feb 07 '22 at 09:14