How To Get Data From List Beyond Threshold Limit Through Calmquery

Most of us face this situation where List Threshold exceeds and the following error is shown.

 

There are many ways to overcome List Threshold, like increasing the threshold value, but it is not recommmended by Microsoft as it creates performance problems.

I have created a scenario where List Threshold has increased and we need to overcame the situation by using List item collection position.

Go to Central Administration > Manage Web Applications > General Settings > Resource Throttling > List View Threshold.

Below is the screenshot of resource throttling which has been set to 2000.

I have created a list by the name Test and created 2432 items in it.

Below is the code that I have used to fetch all 2432 items in single query.

  1. DataTable dt = new DataTable();  
  2. dt.Columns.Add("Name1"typeof(string));  
  3. dt.Columns.Add("ID"typeof(int));  
  4. using(SPSite site = new SPSite(SPContext.Current.Site.ID)) {  
  5.     using(SPWeb web = site.OpenWeb()) {  
  6.         SPList list = web.Lists.TryGetList("Test");  
  7.         SPListItemCollectionPosition itemPosition = null;  
  8.         while (true) {  
  9.             SPQuery camlQuery = new SPQuery();  
  10.             camlQuery.ListItemCollectionPosition = itemPosition;  
  11.             camlQuery.RowLimit = 2000;  
  12.             camlQuery.ViewFields = "<FieldRef Name='Name1'/><FieldRef Name='ID'/>";  
  13.             camlQuery.ViewFieldsOnly = true;  
  14.             camlQuery.Query = "<View></View>";  
  15.             SPListItemCollection listItems = list.GetItems(camlQuery);  
  16.             itemPosition = listItems.ListItemCollectionPosition;  
  17.             DataTable dtitems = listItems.GetDataTable();  
  18.             dt.Merge(dtitems);  
  19.             dt.AcceptChanges();  
  20.             if (itemPosition == null) {  
  21.                 break// TODO: might not be correct. Was : Exit While  
  22.             }  
  23.             //Page.Response.Write(itemPosition.PagingInfo);  
  24.         }  
  25.     }  
  26. }  
  27. if (dt != null && dt.Rows.Count > 0) {  
  28.     GridView1.DataSource = dt;  
  29.     GridView1.DataBind();  
  30. }  
Below is the screenshot for data in the webpart.



Note

Ensure that the below three properties are set before setting Query property for SPQuery.

  1. camlQuery.ListItemCollectionPosition = itemPosition;  
  2. camlQuery.ViewFieldsOnly = true;  
  3. camlQuery.RowLimit = 2000;