Many times we want to display data present in SPList into datagrid. However we don't show all record at any time, instead we display limited records in a grid. Here is the code to paginate through SPlist.
private SPListItemCollection getItemCollection(SPList objList, int pageSize, int pageIndex, string strSortFieldName, string strdatatype, bool blAscendingTrueFalse, string strViewFilds, string strQuery)
{
SPQuery spQry = null;
if (pageIndex < 2)
{
spQry = new SPQuery();
spQry.RowLimit = (uint)pageSize;
spQry.ViewFields = strViewFilds;
spQry.Query = strQuery + "<OrderBy><FieldRef Name=\"" + strSortFieldName + "\" Ascending=\"" + blAscendingTrueFalse + "\" /></OrderBy>";
}
else
{
spQry = new SPQuery();
spQry.RowLimit = (uint)((pageIndex - 1) * pageSize);
spQry.ViewFields = "<FieldRef Name='Id'/><FieldRef Name='" + strSortFieldName + "'/>";
spQry.Query = strQuery + "<OrderBy><FieldRef Name=\"" + strSortFieldName + "\" Ascending=\"" + blAscendingTrueFalse + "\" /></OrderBy>";
SPListItemCollection objItemCollection = objList.GetItems(spQry);
spQry = new SPQuery();
spQry.RowLimit = (uint)pageSize;
spQry.ViewFields = strViewFilds;
spQry.Query = strQuery + "<OrderBy><FieldRef Name=\"" + strSortFieldName + "\" Ascending=\"" + blAscendingTrueFalse + "\" /></OrderBy>"; ;
SPListItemCollectionPosition objSPListColPos = null;
if (strdatatype.ToUpper() == "DATETIME")
{
objSPListColPos = new SPListItemCollectionPosition("Paged=TRUE"
+ "&p_" + strSortFieldName + "=" + SPEncode.UrlEncode(System.DateTime.Parse(objItemCollection[objItemCollection.Count - 1][strSortFieldName].ToString()).ToUniversalTime().ToString("yyyyMMdd hh:mm:ss"))
+ "&p_ID=" + objItemCollection[objItemCollection.Count - 1]["ID"].ToString());
}
else
{
objSPListColPos = new SPListItemCollectionPosition("Paged=TRUE"
+ "&p_" + strSortFieldName + "=" + objItemCollection[objItemCollection.Count - 1][strSortFieldName].ToString()
+ "&p_ID=" + objItemCollection[objItemCollection.Count - 1]["ID"].ToString());
}
spQry.ListItemCollectionPosition = objSPListColPos;
}
return objList.GetItems(spQry);
}
Where,
objList = SPlist Object.
pageSize = datagrid pagesize.
pageIndex = PageIndex.
strSortFieldName = Name of Field on which data is sorted.
strdatatype = DataType of sort field (ie strSortFieldName).
blAscendingTrueFalse = Sort type ie. Ascending or descending.
strViewFilds = string containing the view fields.
strQuery = String containing query to fetch results.