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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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;
	}
}

Summary

In this i felt all things are simple. Only Paging info, list item position, first item and last item need to set properly.

Hope this helps.
Thanks!
Avinash

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

posted on 2012-11-18 15:57  ilawrence  阅读(1578)  评论(2编辑  收藏  举报