Sunday, March 8, 2015

Retrive List Data using paging



SharePoint List Pagination using SPListItemCollectionPosition


http://sharepoint.infoyen.com/2012/03/06/sharepoint-list-pagination-using-splistitemcollectionposition/

Description
This article will show you how to apply paging with sorting on search grid which gets data from sharepoint list by using SPQuery and SPListItemCollectionPosition.
Requirement:-
I have search page which is divided in 2 part; Search filter criteria and other is display result in grid. This page query to sharepoint list using object model and display result.
By thinking of performance; you will never try to get all results from sharepoint list. You have to query page by page. I mean query sharepoint list only for 10 page (page size=10) and display data.
Here I am giving detail about how to query for 10 page and get data. Then display pagination.
Precisely my page will do below things:-
1. Put caml query (only for page size which is set to 10 in my example) on sharepoint list
2. Filter on folder basis
3. Apply sorting
4. Display paging on search result page.
My hunt On Google:-
I have search on google lots but no where I find proper solution which handle sorting, paging with filter using caml query and folder query.
But still I like msdn and below 2 blogs from where I got basic understanding
http://www.directsharepoint.com/2011/03/step-by-step-guide-to-implement-paging.html
http://blogs.msdn.com/b/colbyafrica/archive/2009/02/19/learning-sharepoint-part-vi-list-pagination.aspx
The Code 
Below are 2 classes SearchDocuments and SearchPaging.
SearchDocuments: This class is code behind file my user control which manage search.
SearchPaging: This class set property for search results and search paging.

Hi Sai,

I have already mentioned the steps in article. However see below a quick glance:-

1. Create a user control, place your all filters and place grid there to see results.
2. In code behind file; write your logic to get items from sharepoint list.
3. Then bind into your grid.
4. Now the issue is paging. Now you can use my article :)

A) Use my logic to create prev and next link button link.
B) Use my logic to bind your filters
C) Use my logic to create paging info string which is constructed using PreviousPageString or nextPageString.
D) Use my method “GetAllSearch” to get document from sharepoint list.

Note: My blogs are not complete copy paste to get solution. You need to take logic and may be few functions which you can merge into your code to mitigate your business needs.
public partial class SearchDocuments : System.Web.UI.UserControl
{
public string Next
{
get { return ViewState["Next"] == null ? string.Empty : (string)ViewState["Next"]; }
set { ViewState["Next"] = value; }
}
public string Previous
{
get { return ViewState["Previous"] == null ? string.Empty : (string)ViewState["Previous"]; }
set { ViewState["Previous"] = value; }
}
// store column name for order by query
private string DataSortExpression
{
get { return ViewState["DataSortExpression"] == null ?
Constant.SearchResultColumnDocumentName : (string)ViewState["DataSortExpression"]; }
set { ViewState["DataSortExpression"] = value; }
}
// store direction; Acending or decending for order by query
private SortDirection DataSortDirection
{
get { return ViewState["DataSortDirection"] == null ?
SortDirection.Ascending : (SortDirection)ViewState["DataSortDirection"]; }
set { ViewState["DataSortDirection"] = value; }
}

/// <summary>
/// This function get call on search button and prev or next link
/// this manage paging and grid results.
/// </summary>
private void BindListData(Dictionary<string, string> searchFilters,
string pagingInfo, int currentPageNumber)
{
try
{
ViewState["CurrentPage"] = currentPageNumber.ToString();
uint rowCount = 10; //Page Size

// below 2 string format are good if you have orderby in your caml query.
string nextPageString = "Paged=TRUE&p_FSObjType=0&p_{0}={1}&p_ID={2}";
string PreviousPageString = "Paged=TRUE&p_FSObjType=0&PagedPrev=TRUE&p_{0}={1}&p_ID={2}";
/*
 below 2 string format are good if you dont have orderby in your caml query.
 string nextPageString = "Paged=TRUE&p_{0}={1}&p_ID={2}";
 string PreviousPageString = "Paged=TRUE&PagedPrev=TRUE&p_{0}={1}&p_ID={2}";
*/
int pageOrderNumber = ((currentPageNumber - 1) * Convert.ToInt32(rowCount)) + 1;
string orderBy = string.Empty;
// set order by query.
// By default DataSortExpression value is ID. but on click of sorting it change column value
if (DataSortDirection == SortDirection.Ascending)
orderBy = @"<OrderBy><FieldRef Name='" +
DataSortExpression + "' Ascending='True' /></OrderBy>";
else
orderBy = @"<OrderBy><FieldRef Name='" +
DataSortExpression + "' Ascending='False' /></OrderBy>";

// it generate caml query based on my search filters
// you can write you own logic to build caml query
string query = GetQuery(searchFilters);
query = string.Concat(query, orderBy); // add order by in query
// get folder name from you search filter criteria
string folderName = searchFilters.TryGetValue("FolderName", out folderName);

// pass paging info, query row limit in below function
// this function will return object of my custom class which hold datatable object and paging info
// Once current function ends; You will find detail about GetAllSearch function in this blog
SearchPaging searchData = GetAllSearch(query, pagingInfo, rowCount, pageOrderNumber, folderName);

if (searchData != null && searchData.SearchItems != null)
{
SPListItemCollectionPosition itemPosition = searchData.ItemCollPosition;
// ctlGrid is a object of my SPGridView
ctlGrid.DataSource = searchData.SearchItems;
ctlGrid.DataBind();
this.ResultPanel_Search.Visible = true;

//now we need to identify if this is a call from next or first
if (null != itemPosition)
{
  nextPageString =
  string.Format(nextPageString, DataSortExpression,
archData.LastItem[DataSortExpression], searchData.LastItem.ID);
}
else
{
nextPageString = string.Empty;
}

if (currentPageNumber > 1)
{
 PreviousPageString =
 string.Format(PreviousPageString, DataSortExpression,
searchData.FirstItem[DataSortExpression], searchData.FirstItem.ID);
}
else
{
PreviousPageString = string.Empty;
}

if (string.IsNullOrEmpty(nextPageString))
{
LinkButtonNext.Visible = false;
}
else
{
LinkButtonNext.Visible = true;
}

if (string.IsNullOrEmpty(PreviousPageString))
{
LinkButtonPrevious.Visible = false;
}
else
{
LinkButtonPrevious.Visible = true;
}

ViewState["Previous"] = PreviousPageString;
ViewState["Next"] = nextPageString;

string pageNumber = string.Empty;

if (currentPageNumber == 1)
pageNumber = Convert.ToString(((currentPageNumber - 1) * Convert.ToInt32(rowCount)) + 1);
else
pageNumber = Convert.ToString((currentPageNumber));

lblPaging.Text = "Page - " + pageNumber;

ctlContainerUpdatePanel.Update();

}
else
{
ctlContainerUpdatePanel.Update();
this.ResultPanel_Search.Visible = false;
this.ErrorMessageLabel.Text = "No records found";
}
}
catch (Exception ex)
{
// manage exception
}
}

/// <summary>
/// This function query to sharepoint list and return SearchPaging class object
/// which holde results and paging info
/// </summary>
private SearchPaging GetAllSearch(string queryXML, string pagingInfo, uint rowCount,
int pageOrderNumber, string folderName)
{
SPQuery query = new SPQuery();
query.Query = queryXML;
query.RowLimit = rowCount;
if (!string.IsNullOrEmpty(pagingInfo))
{
SPListItemCollectionPosition position = new SPListItemCollectionPosition(pagingInfo);
query.ListItemCollectionPosition = position;
}

query.ViewFields = string.Concat(
"<FieldRef Name='ID' />",
  "<FieldRef Name='Title' />");

// assign folder name
if (!String.IsNullOrEmpty(folderName))
{
SPFolder searchFolder = list.RootFolder.SubFolders[folderName];
query.Folder = searchFolder;
query.ViewAttributes = "Scope="Recursive"";
}

SPListItemCollection itemColl = list.GetItems(query);

// SearchPaging is my custom class which have some get set.
// i have copied code of this class in bottom for your reference

SearchPaging searchPaging = new SearchPaging(itemColl.GetDataTable()); // set result datatable
searchPaging.ItemCollPosition = itemColl.ListItemCollectionPosition; // set position object
searchPaging.FirstItem = itemColl[0]; // set first item of page
searchPaging.LastItem = itemColl[itemColl.Count - 1]; // set last item of page

return searchPaging;
}

protected void linkBtn_Search_Click(object sender, EventArgs e)
{
try
{
ViewState["Next"] = string.Empty;
ViewState["Previous"] = string.Empty;
ViewState["DataSortExpression"] = Constant.SearchResultColumnDocumentName;
// get filters and store into Dictionary object
// i store actual internal column value as key, so that i can use in my caml query
Dictionary<string, string> searchFilters = GetSearchData();
if (searchFilters.Count > 0)
{
BindListData(searchFilters, ViewState["Next"] as string, 1);
}
}
catch(Exception ex)
{
// manage exception
}
}

protected void LinkButtonPrevious_Click(object sender, EventArgs e)
{
Dictionary<string, string> searchFilters = GetSearchData();
if (searchFilters.Count > 0)
BindListData(searchFilters, ViewState["Previous"] as string, Convert.ToInt32(ViewState["CurrentPage"]) - 1);
}

protected void LinkButtonNext_Click(object sender, EventArgs e)
{
Dictionary<string, string> searchFilters = GetSearchData();
if (searchFilters.Count > 0)
BindListData(searchFilters, ViewState["Next"] as string, Convert.ToInt32(ViewState["CurrentPage"]) + 1);
}    

}

public partial class SearchPaging
{
public SPListItemCollectionPosition ItemCollPosition { get; set; }
public SPListItem FirstItem { get; set; }
public SPListItem LastItem { get; set; }
private DataTable searchItems;
public int SearchResultCount { get; set; }
public DataTable SearchItems
{
get{return searchItems;}
}

public SearchPaging() { }

public SearchPaging(DataTable SearchItems)
{
searchItems = SearchItems;
}
}

-----------------------------------------

PagingInfo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using System.Text.RegularExpressions;

namespace SPListItemCollectionPositionExample
{
    public static class PagingInfo
    {
        public static void SavePageInfo(StateBag viewState, string pagingInfo)
        {
            viewState["PagingInfo"] = pagingInfo;
        }

        public static SPListItemCollectionPosition GetNextPagePosition(StateBag viewState)
        {
            string pagingInfo = string.Empty;

            if (viewState["PagingInfo"] != null)
                pagingInfo = viewState["PagingInfo"].ToString();

            return new SPListItemCollectionPosition(pagingInfo);
        }

        /// <summary>
        /// Returns the Previous Page information (not accurage when items are deleted in between / ID sequencing problem)
        /// </summary>
        /// <param name="viewState"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public static SPListItemCollectionPosition GetPrevPagePosition(StateBag viewState, int pageSize)
        {
            string pagingInfo = string.Empty;

            if (viewState["PagingInfo"] != null)
            {
                pagingInfo = viewState["PagingInfo"].ToString();

                if (!string.IsNullOrEmpty(pagingInfo))
                {
                    string pIDKeyValue = new Regex("p_ID=(?'p_ID'\\d+)").Match(pagingInfo).Value;
                    string pIDValue = pIDKeyValue.Replace("p_ID=", string.Empty);
                    if (!string.IsNullOrEmpty(pIDValue))
                    {
                        int value = int.Parse(pIDValue);

                        value -= (pageSize * 2);
                        if (value < 1)
                            pagingInfo = string.Empty;
                        else
                            pagingInfo = pagingInfo.Replace(pIDKeyValue, "p_ID=" + value.ToString());
                    }
                }
            }

            return new SPListItemCollectionPosition(pagingInfo);
        }
    }
}


--------------
VisualWebPart1UserControl

<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="VisualWebPart1UserControl.ascx.cs" Inherits="SPListItemCollectionPositionExample.VisualWebPart1.VisualWebPart1UserControl" %>
<style type="text/css">
    .style1
    {
        width: 100%;
    }
</style>

<table class="style1">
    <tr>
        <td>
            <asp:Button ID="CreateDataButton" runat="server" 
                onclick="CreateDataButton_Click" Text="Create Data" Width="175px" />
            <asp:Label ID="Label1" runat="server" 
                Text="Create a Contact List of 1000 Items"></asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
    </tr>
    <tr>
        <td>
            <asp:Button ID="ShowDataButton" runat="server" Text="Show Data" 
                onclick="ShowDataButton_Click" />
            <asp:Button ID="NextPageButton" runat="server" Text="Next Page" 
                onclick="NextPageButton_Click" />
        </td>
    </tr>
    <tr>
        <td>
            <asp:GridView ID="GridView1" runat="server">
            </asp:GridView>
        </td>
    </tr>
    <tr>
        <td>
            &nbsp;</td>
    </tr>
</table>
----------------

VisualWebPart1UserControl.ascx.cs

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace SPListItemCollectionPositionExample.VisualWebPart1
{
    public partial class VisualWebPart1UserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void CreateDataButton_Click(object sender, EventArgs e)
        {
            using (SPWeb web = SPContext.Current.Web)
            {
                string listName = "Contacts 1000";
                SPList list = null;

                // Create Lists
                try
                {
                    list = web.Lists[listName];
                }
                catch
                {
                    web.Lists.Add(listName, "A Contact List of 1000 items", SPListTemplateType.Contacts);
                    list = web.Lists[listName];

                    // Create Data
                    for (int i = 1; i <= 1000; i++)
                    {
                        SPListItem item = list.Items.Add();
                        item["First Name"] = "First Name " + i.ToString();
                        item["Last Name"] = "Last Name " + i.ToString();

                        item.Update();
                    }
                }
            }
        }

        protected void ShowDataButton_Click(object sender, EventArgs e)
        {
            SPQuery query = new SPQuery();
            query.RowLimit = 10;
            query.ViewFields = "<FieldRef Name=\"Title\" />" +  /* Title is LastName column */
                            "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
            string listName = "Contacts 1000";
            SPList list = SPContext.Current.Web.Lists[listName];

            SPListItemCollection collection = list.GetItems(query);

            PagingInfo.SavePageInfo(ViewState, collection.ListItemCollectionPosition.PagingInfo);

            GridView1.DataSource = collection.GetDataTable();
            GridView1.DataBind();
        }

        protected void NextPageButton_Click(object sender, EventArgs e)
        {
            SPQuery query = new SPQuery();
            query.RowLimit = 10;
            query.ViewFields = "<FieldRef Name=\"Title\" />" +  /* Title is LastName column */
                            "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
            string listName = "Contacts 1000";
            SPList list = SPContext.Current.Web.Lists[listName];

            /* New */
            query.ListItemCollectionPosition = PagingInfo.GetNextPagePosition(ViewState);

            SPListItemCollection collection = list.GetItems(query);

            PagingInfo.SavePageInfo(ViewState, collection.ListItemCollectionPosition.PagingInfo);

            GridView1.DataSource = collection.GetDataTable();
            GridView1.DataBind();
        }

        protected void PrevPageButton_Click(object sender, EventArgs e)
        {
            SPQuery query = new SPQuery();
            query.RowLimit = 10;
            query.ViewFields = "<FieldRef Name=\"Title\" />" +  /* Title is LastName column */
                            "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
            string listName = "Contacts 1000";
            SPList list = SPContext.Current.Web.Lists[listName];

            /* New */
            query.ListItemCollectionPosition = PagingInfo.GetPrevPagePosition(ViewState, 10);

            SPListItemCollection collection = list.GetItems(query);

            PagingInfo.SavePageInfo(ViewState, collection.ListItemCollectionPosition.PagingInfo);

            GridView1.DataSource = collection.GetDataTable();
            GridView1.DataBind();
        }
    }
}