Wednesday, June 27, 2012

Delete all items from SharePoint list programmatically

In this article we will discuss how to delete all items programmatically by using SharePoint object model. Till now if you are thinking you will call the delete() method, then for sure it is not going to work. You can also check my last article on Add Retrieve SharePoint list items using Object Model.

Suppose you want to delete all items from the SharePoint List once the item count greater than 2000. If you will simply call the Delete() method in a for each statement  like below then it is not going to work, because the itemcount will change whenever you will delete one item. So after that it will delete one item at a time.

Wrong Approach:

 void DeleteListItems()
        {
            SPSite myTopSite = SPContext.Current.Site;
            {
                SPWeb myTopWeb = SPContext.Current.Site.RootWeb;
                {
                    SPList list = myTopWeb.Lists.TryGetList("MyCustomList");

                    if (list != null)
                    {
                        if (list.ItemCount > 2000)
                        {
                            foreach (SPListItem item in list.Items)
                            {
                                item.Delete();
                            }
                        }
                    }
                }
            }
        }

If you want to know more about TryGetList, then you can read a very good article on TryGetList here.

-->
Correct Approach:

 void DeleteListItems()
        {
            SPSite myTopSite = SPContext.Current.Site;
            {
                SPWeb myTopWeb = SPContext.Current.Site.RootWeb;
                {
                    SPList list = myTopWeb.Lists.TryGetList("MyCustomList");
                    System.Collections.Hashtable htItems = new System.Collections.Hashtable(list.ItemCount);
                    if (list != null)
                    {
                        if (list.ItemCount > 2000)
                        {
                            foreach (SPListItem item in list.Items)
                            {
                                //item.Delete();
                                htItems.Add(item.ID, null);

                                foreach (int ID in htItems.Keys)
                                    list.Items.DeleteItemById(ID);

                                htItems.Clear();
                            }
                        }
                    }
                }
            }
        }

Here rather deleting the item directly, we are keeping the item id's in a Hash table and then we are deleting the list item based on the ID.