I had a requirement to display data from a sharepoint list in a silverlight user control with pagination.
Here is the logic in the server side.
Following code block will fetch specified number of records from a single sharepoint list.
using (SPSite site = new SPSite(“http://localhost/”))
{
using (SPWeb web = site.OpenWeb())
{
uint recordsPerPage = 15;
string pagingData = string.Empty;
string strQuery = “<OrderBy><FieldRef Name=’Date_x0020_Edited’ Ascending=’false’/></OrderBy>”;
string ViewFields = “<FieldRef Name=’Title’/>” +
“<FieldRef Name=’Description’ />” +
“<FieldRef Name=’Date Edited’ />” +
“<FieldRef Name=’Market’ />” +
“<FieldRef Name=’Role’ />” +
“<FieldRef Name=’First Name’ />” +
“<FieldRef Name=’Last Name’ />”;
SPQuery query = new SPQuery();
// Sets the maximum number of records to be fetched from the query.
query.RowLimit = recordsPerPage;
// The CAML query to be applied over the list.
query.Query = strQuery;
/*Collection of SPFields(List Columns) needed on the output record set.
If left empty will retrieve all columns
Just like the diference bet ween SELECT * and SELECT Title,Description….*/
query.ViewFields = ViewFields;
/* This variable is used to set the page number.
This is the main part in paging logic.
To get the first page pass String.Empty(do not pass null) as the parameter for SPListItemCollectionPosition’s constructor.*/
SPListItemCollectionPosition position = new SPListItemCollectionPosition(pagingData);
query.ListItemCollectionPosition = position;
SPList list = (SPList)web.Lists["Customers"];
SPListItemCollection Items = list.GetItems(query);
// Fill your entity objects here
/* After the query is executed, position.PagingInfo will contain the ID of the last element fetched, together with a flag. If it is null then there is no further data in the list to query. So to get the records for next page, we need to pass this */
if (position.PagingInfo != null)
{
pagingData = position.PagingInfo;
}
else
{
// No more records in sharepoint list
}
}
}
There are some disadvantages in this approach.
1) It cannot be applied for multiple sharepoint lists at a time. Even if you maintain a List of pagingData for every lists, the logic will become cumbersome.
2) Importantly this method holds good when we navigate from page1,to 2,3 … Random jumping to pages is not possible. This is because to navigate to page n, we need the ID of the last record of page n-1, which we cannot get without navigating to page n-1.
Full working example with source code on Sharepoint Paging
is posted at http://www.directsharepoint.com/2011/03/step-by-step-guide-to-implement-paging.html