Wednesday, September 23, 2009

Deleting Items in a sharepoint list

How to delete items in sp list?
Whenever we are thinking about this scenario, suddenly the code comes in the mind is create foreach loop and loop through each items and delete the items.
But the problem is we cannot the the list items by this way. It will give the error like "Collection was modified; enumeration operation may not execute."
So to overcome this problem we need to write the code in differently.

int iCount = list.Items.Count;//Its allways better practice to assign the the count to some variable if we use list.Items.Count in for loop it will get the count record from database as many times as for loop will run.
int j ;
for(int i=iCount-1; i>=0;i--)
{
j = i;
list.Item[j].Delete()
}

Same logic will be applied to all share point collection.

No comments:

Post a Comment