Friday, July 8, 2011

How to delete items from SharePoint List

Many of us might think whats new in deleting the item from Sharepoint List but there are some interesting facts to understand about this process.
You might come across this wierd error
  "Collection was modified; enumeration operation may not execute"
The error is same irrespective of  using a for or a foreach loop.
Let me Explain what happens in the background when delete using the follolwing code
                    SPList gallery = site.Lists["Your List"];
                    SPListItemCollection itemCol = gallery.Items;
                    foreach(SPListItem item in itemCol)
                    {
                        item.Delete();
                       gallery.update();                     
                    }                                   
Now whenever this code executes for each item deletion as the number of items gets deleted ,the second item gets the first index and that the reason for error.
You can also do the same like this
for (int i = 0; i < list.Items.Count; i++) {    
    list.Items.Delete(0);
}
This skips the items or randomly deletes the items in some scenarios.
So Best ways for deletion process:
Method 1 when deleting all items :
for (int i = list.Items.Count - 1; i >= 0; i--) {
    list.Items.Delete(i);
}
Method 2:IF a condition as to be met before deletion
So the best way of doing the deletion process is      
                    SPList gallery = site.Lists["YourList"];
                    SPListItemCollection itemCol = gallery.Items;
                    for (int i = itemCol.Count -1;i>=0; i--)
                 {
                        if (itemCol[i].Title.Equals("SomeName"))
                        {
                           itemCol[i].Delete();
                           gallery.Update();
                        }
                    }
              

No comments:

Post a Comment