4

I have an issue around using SPListItem.Delete. I am fetching some list items (less than 20) and looping through them using a for loop. In each iteration of the loop, I retrieve a SPListItem using SPListItemCollection.GetItemByID method. And then I execute a Delete(). However, it only deletes half the items.

Can some one please help?

Code follows:

 SPListItemCollection listItems = Get_Items();
                 for (int i=0; i<listItems.Count; i++)

            {
                SPListItem currentListItem = listItems.GetItemById(listItems[i].ID);

                currentListItem.Delete();

            }

Thanks,

4
  • Can you post your code for us to see? Commented Feb 3, 2020 at 21:32
  • Done. code edited to the post. thanks Commented Feb 3, 2020 at 22:19
  • Do you get any errors?
    – willman
    Commented Feb 3, 2020 at 22:34
  • No errors, it consistently just deletes exactly half of what is in the listitemcollection. So if I have 20 start with it will delete 10, then it will delete 5, etc. Commented Feb 3, 2020 at 23:00

1 Answer 1

4

Try to start from i=listItems.Count-1 to avoid looping on items that already deleted!

for(int i=listItems.Count-1 ; i >= 0 ; i--)
    {
          SPListItem currentListItem = ListName.Items[i];
          currentListItem .Delete();
     }

or

for(int i=listItems.Count-1 ; i >= 0 ; i--)
    {
          SPListItem currentListItem = listItems.GetItemById(listItems[i].ID);
          currentListItem .Delete();
     }
3
  • didn't work. I get Specified argument was out of the range of valid values. Commented Feb 4, 2020 at 0:06
  • changed it to i-- and >=0 and now working. Thanks Mohammed appreciate it. for (int i = listItems.Count - 1; i >= 0; i--) Commented Feb 4, 2020 at 0:08
  • Most welcome ;) the answer updated to be helpful fo future coming users Commented Feb 4, 2020 at 0:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.