Tuesday, May 19, 2009

Custom List Paging in OOB way

using (SPSite mySite = new SPSite("site url"))
{
using (SPWeb myWeb = mySite.OpenWeb())
{
SPList myList = myWeb.Lists["List Name"];
if (myList != null)
{
SPQuery myQuery = new SPQuery();

myQuery.Query = "";

myQuery.RowLimit = 10;

// Set the paging information with query object in case it is required.
string strPageInfo = string.Empty;

// Prepare the pageInfo string for Previous Page.
if (strEvent == "PREVIOUSPAGE")
{
strPageInfo = "Paged=TRUE&PagedPrev=TRUE&p_" + strSortFieldName + "=" + strSortFieldLastValue + "&p_ID=" + strPageID;
myQuery.ListItemCollectionPosition = new SPListItemCollectionPosition(strPageInfo);
}
// Prepare the pageInfo string for Next Page.
else if (strEvent == "NEXTPAGE")
{
strPageInfo = "Paged=TRUE&p_" + strSortFieldName + "=" + strSortFieldLastValue + "&p_ID=" + strPageID;
myQuery.ListItemCollectionPosition = new SPListItemCollectionPosition(strPageInfo);
}

SPListItemCollection myItems = myList.GetItems(myQuery);
if (myItems != null)
{
// Gets the result set
DataTable dtResult = myItems.GetDataTable();
}
myQuery = null;
myList = null;
}
}
}

Notes:
· strEvent (string) – variable that indicates which event is reuiured “NEXTPAGE” or “PREVIOUSPAGE”.
· strSortFieldName (string) – The list field name based on which sorting is required.
· strSortFieldLastValue (string) – The sorting list field’s value corresponding to the last row being displayed at your UI (eg. GridView).
· strPageID (string) – The list field “ID” value for the last item on UI (eg. GridView).
· isAscending (string) – “true” or “false”, indicates the order of sorting.

1 comment:

  1. Nice..
    You can also visit my blog which explain how to apply paging with sorting,caml query, folder query on sharepoint list by using SPQuery and SPListItemCollectionPosition.

    SharePoint List Pagination using SPListItemCollectionPosition

    ReplyDelete