Friday, August 24, 2012

SharePoint 2012: Clear/Empty a List

I took a business trip out to Omaha to automate some reporting and SharePoint is what they use so SharePoint is what I need to use. I was able to figure out how to clear or empty a list despite little to no help from any good online sources. Here is the code I used:

public void ClearList(string listName)
{
     List list = client.Web.Lists.GetByTitle(listName);

     ListItemCollection listItemColl = list.GetItems(CamlQuery.CreateAllItemsQuery());

     client.Load(listItemColl);
     client.ExecuteQuery();

     foreach (ListItem item in listItemColl)
     {
         list.GetItemById(item.Id).DeleteObject();
         list.Update();
     }

     client.ExecuteQuery();
}

Basically I have a method that takes in a list name, it then:
  1. Gets the list via "GetByTitle" method
  2. Gets all the items of that list and uses the CreateAllItemsQuery method of the CamlQuery class to get all the items.
  3. Load the items and execute.
  4. Loop through, get the item, delete the item, update the list.
  5. Finally, it executes and deletes everything off the list.
If you found this useful or have any questions please comment or message me, as well, follow me on twitter: @WebDevProblems.

No comments:

Post a Comment