If somebody like the post and its helpful in your work then, add comments.

Monday, September 6, 2010

SharePoint 2010 : Paging in the SharePoint list

Hi,

Paging in the SharePoint 2010 list is done using the

SPListItemCollectionPosition 

The SPListItemCollectionPosition class supports paging through data sets, storing the state that is needed to get the next page of data for a specific view of a list.

ListItemCollectionPosition

Gets or sets an object that is used to obtain the next set of rows in a paged view of a list. The below code I have refined from the following link. It will return the given page like page 3, items say 4.



public static SPListItemCollection ExecuteCAMLToRetrieveListItemsInPages( string listName, string viewName, 
string caml, string[] columnNames, int pageIndex, int pageItemCount)
{
SPListItemCollection postDetailsItems = null;
using (SPSite Site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb sharePointWeb = Site.AllWebs[XYZ])
{
// Check if the SharePoint web object is not null or not.
if (sharePointWeb == null)
{
}
// Get the Post List
SPList postList = sharePointWeb.Lists[listName];
// Get the SPLIst View
SPView listView = postList.Views[viewName];
SPQuery query = new SPQuery(listView);
query.Query = caml;
// Retrieve the items for the last page. E.g.: If request is for 5th page and item count/page=10 then row limit will retrieve
//40 items and 40th item will be used to get the column details which will be used for pagination.
query.RowLimit = (uint)(pageItemCount * (pageIndex - 1));
postDetailsItems = postList.GetItems(query);
// Get the previous page last item position. Use this item to retrieve the column details which will be used for pagination.
int previousPageLastItemPosition = postDetailsItems.Count - 1;
StringBuilder columnBuilder = new StringBuilder();
// Form the paging filter query string
if (columnNames != null)
{
foreach (string column in columnNames)
{
// Make sure that if the field value is mandatory and if you are passing it as NULL then SPList.GetItems will throw exception.
string columnValue =
(postDetailsItems[previousPageLastItemPosition][column] == null) ? string.Empty : postDetailsItems[previousPageLastItemPosition][column].ToString();
// Check if the value is null or empty
columnBuilder.Append("&p_" + column + "=" + columnValue);
}
}
query = new SPQuery(listView);
query.Query = caml;
// Create Paging Information which will be used for retrieving paging based items
SPListItemCollectionPosition objSPListColPos = new SPListItemCollectionPosition("Paged=TRUE" + columnBuilder.ToString());
query.RowLimit = uint.Parse(pageItemCount.ToString());
query.ListItemCollectionPosition = objSPListColPos;
// Execute the CAML query.
postDetailsItems = postList.GetItems(query);
}
} return postDetailsItems;
}