Tuesday, July 14, 2009

Paging SPList with ListItemCollectionPosition

Using ListItemCollectionPosition to make paging is somehow tricky, you have to take care if you are using order in your CAML query that you need to make paging on, as the parameters passed to ListItemCollectionPosition like “Paged=TRUE&p_ID=8” is not just to say star from the itemID = 8, when it is used like this, the paging will page based on the default order.

But if you want to order by example the created date in your CAML query, so you have to include that also in your ListItemCollectionPosition parameters, ex:

Paged=TRUE&p_Created=20091208%2006%3a24%3a35&p_ID=8

Where p_Created=20091208%2006%3a24%3a35 is the created date of the itemID = 8

If it is not used like that you will see unrealistic output.
A good idea to make paging is by making an array that its index will be the page index, and its value will be the ListItemCollectionPosition.PagingInfo like this:

void SetupPager(SPList tmpList, string queryString)
{
    myPagingData.Add("Paged=TRUE");
    SPQuery query = new SPQuery();
    query.Query = queryString;
    query.RowLimit = 5;
    do
    {
        SPListItemCollection itemList = tmpList.GetItems(query);
        query.ListItemCollectionPosition = itemList.ListItemCollectionPosition;
        if (query.ListItemCollectionPosition != null)
        {
            myPagingData.Add(query.ListItemCollectionPosition.PagingInfo);
        }

    }
    while (query.ListItemCollectionPosition != null);

}

The above method can be called in the first time the page is opened, and you can add array to the viewstate and reload it with each postback and pass it to the query like this:
SPListItemCollectionPosition objSPListColPos = new SPListItemCollectionPosition(myPagingData [e.CurrentPage]);
query.ListItemCollectionPosition = objSPListColPos;

2 comments:

Anmol Rehan said...

Using Client Object model please visit
http://www.anmolrehan-sharepointconsultant.com/2011/10/client-object-model-access-large-lists.html

Dan Harvey said...

What happens if an item is deleted or added? Will it be accounted for?