Paging with SharePoint Lists

Let’s say you have a SharePoint web part that displays data from a SharePoint list and you are running into performance issues, as you are simply attempting to display too much information.

One way to resolve this would be to apply paging. Paging is a technique where you only retrieve a chunk of the data instead of all the data which can improve performance.

Two key properties in paging are the page size and the page position (the current page).

In order to apply paging you will need to modify how you are currently retrieving the data. Assuming that you are retrieving all the data from the list, your code might look something like this:

[code language=”csharp”]
SPQuery query = new SPQuery();

query.Query = string.Format(“<Where><Eq><FieldRef Name=’AccountID’ /><Value Type=’Text’>{0}</Value></Eq></Where>”, accountID);

SPListItemCollection items = list.GetItems(query);
[/code]

We will need to update the query object to set the page size, to do that just set the RowLimit property on SPQuery.

[code language=”csharp”]
query.RowLimit = 5;
[/code]

Next, you will need to set the page position. You can do this by setting the ListItemCollection.PagingInfo property on SPQuery. For the initial retrieve we don’t need to set this, but you will need to set it for retrieving the next page. SharePoint will actually give you the PagingInfo you need to retrieve the next page once we’ve executed the query.

[code language=”csharp”]
SPListItemCollection items = list.GetItems(query);

var nextPageInfo = items.ListItemCollectionPosition.PagingInfo; // contains the PagingInfo needed to go to the next page
[/code]

The returned PagingInfo is just a string that will look something like this: “Paged=TRUE&p_ID=5” this is what you will need to retrieve the next page of items.

The “p_ID=5″ is telling SharePoint that it needs to retrieve the 5 (or whatever your page size is) items that come after the item with an ID of 5.

Now to retrieve the next page you will need to set the PagingInfo property on SPQuery.

[code language=”csharp”]
query.ListItemCollectionPosition = new SPListItemCollectionPosition(nextPagingInfo);
[/code]

To go to the previous page you will need to do some extra work, unfortunately SharePoint is not nice enough to give us the PagingInfo needed to go to the previous page.

Here is a simple way to get the PagingInfo for the previous page.

[code language=”csharp”]
var prevPageInfo = string.Format(“PagePrev=True&amp;Paged=TRUE&amp;p_ID={0}”, items[0].ID);
[/code]

The generated string will look something like this “PagePrev=True&Paged=TRUE&p_ID=6”, this is telling SharePoint that it needs to retrieve the 5 (or whatever your page size is) items that come before the item with an ID of 6.

Here’s a little illustration:

Paging with SharePoint lists

This is just the basics of paging with SharePoint lists, if you decide to apply sorting or filtering you will also need to take those into consideration as well.