Click here to Skip to main content
15,885,244 members
Articles / Programming Languages / C#
Article

SharePoint 2010 using SPListItemCollectionPosition for faster results

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
20 Jun 2012CPOL3 min read 34K   417   3   1
Exploring the class SPListItemCollectionPosition and its advantages.

Introduction

In this article we will explore the class SPListItemCollectionPosition and its advantages. This is a server object model type and should be used along with modules executed on the server.

What is SPListItemCollectionPosition?

This class enables Pagination for Lists inside SharePoint. It stores the state of a page and thus helps in fetching the next page in the dataset.

The class can be used along with the SPQuery object.

What are the advantages of SPListItemCollectionPosition?

It provides the following advantages:

  1. Reduced network traffic
  2. Reduced memory
  3. Faster result delivery

Going practical

Now we can try ourselves the usage of SPListItemCollectionPosition. Here we are going to create 1000 list items and fetch 10 at a time. The web part associated will be containing page navigation buttons.

Step 1: Create a Visual WebPart solution.

Create a new Visual WebPart solution and give it a meaningful name.

Image 1

Step 2: Place controls:

Place the following controls for the WebPart.

Image 2

Step 3: Create the Data

Now we need to create a list with 1000 items. The following code does the purpose. Place the code inside the Created Data button click event.

C#
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();
            }
        }
    }
}

Now we can try creating the data by executing the above code. The steps are:

  1. Build the solution
  2. Deploy the solution
  3. Insert WebPart into Page
  4. Click the Create Data button

You can see that inside the Lists link, a new list named Contacts 1000 is created with the following data.

Image 3

Step 4: Show the Data

Now we are ready to show the first 10 list items. Here we are showing only 10 items per page and saving the Page information in the View State of the User Control.

C#
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();
}

Note: Here we are using the SPListItemCollection object to memorize the items fetched. To persist this information between page requests, we are saving it to the ViewState using the PagingInfo class.

You can execute the code and see the results as below:

Image 4

Note: In this case, the ViewState contains the following data: Paged=TRUE&p_ID=10. It stores the last ID of the item displayed. This ID is required for processing the next button.

Step 5: Next page functionality

Following is the code for the Next Page button functionality.

C#
protected void NextPageButton_Click(object sender, EventArgs e)
{
    SPQuery query = new SPQuery();
    query.RowLimit = 5;
    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();
}

The code takes the Page Position from the View State using the PagingInfo class. You can see the following results on executing and clicking the Next button.

Image 5

So this concludes our experiment with the SPListItemCollectionPosition class.

About the Utility class

Following is the body of the PagingInfo class. It is a static class basically doing the SavePageInfo() and GetNextPagePosition() functionalities by saving the Page Info string to the View State and getting back.

C#
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);
    }
}

This concludes the usage of the SPListItemCollectionPosition class.

About the Previous Page functionality

As the SPListItemCollectionPosition is meant for providing paginated results for the next page by storing the ID value of the last item in the page, to perform the functionality of Previous page, we need to work more on getting the ID of the first item in the page. I have added some links that should give an idea of enabling the Previous functionality.

<ph2>References

Summary

In this article we have explored the advantages and use of SPListItemCollectionPosition. In real world scenarios, this class provides faster results with reduced network traffic involved. The attachment contains the source code we discussed. You can download and install it to your SharePoint site for testing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
United States United States
Jean Paul is a Microsoft MVP and Architect with 12+ years of experience. He is very much passionate in programming and his core skills are SharePoint, ASP.NET & C#.

In the academic side he do hold a BS in Computer Science & MBA. In the certification side he holds MCPD & MCTS spanning from .Net Fundamentals to SQL Server.

Most of the free time he will be doing technical activities like researching solutions, writing articles, resolving forum problems etc. He believes quality & satisfaction goes hand in hand.

You can find some of his work over here. He blogs at http://jeanpaulva.com

Comments and Discussions

 
QuestionHow to query more than one list? Pin
MartinLui7-Jan-14 17:53
MartinLui7-Jan-14 17:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.