Delete MOSS 2007 List Item using C# – Microsoft Sample code doesn’t work

Reading Time: 1 minute

Below is the Code to Delete List Item used by Microsoft Sample

spListCollection = spWeb.Lists[“ActualAmounttrack”].Items;
int itemCount = spListCollection.Count;
for (int k = 0; k < itemCount; k++)
{
SPListItem item = spListCollection[k];

if (IdeaId == item[“Title”].ToString())
{
spListCollection.Delete(k);
}
}

Its not Working.

Why the above code is not working – If you need to loop through the ListItemCollection to delete multiple ListItems, your code will not work. When you attempt to delete the last ListItem, you will receive a boundary exceeded exception. The index to the ListItemCollection should always = 0.

Solution:

Working code

spListCollection = spWeb.Lists[“ActualAmounttrack”].Items;
int itemCount = spListCollection.Count;

for (int k = itemCount; k > 0; k – -)
{
int id = k – 1;
SPListItem item = spListCollection[id];

if (IdeaId == item[“Title”].ToString())
{
spListCollection.Delete(id);
}
}

Communities Tagged : Technology
Tagged: MOSS , Delete List Items

2 Responses to “Delete MOSS 2007 List Item using C# – Microsoft Sample code doesn’t work”

  1. Prabakaran, Vinod Kumar Says:

    Very Informative Jenkins.

    A point more to add to this post.

    To Edit Item
    —————-

    The code will not work unless we have Item.Update() or Item.SystemUpdate() at the end of the loop.

  2. NS, Jenkins Says:

    Thank you

    You added information about edit item is informative and its usefull for my blog visiters.

Published by NS, Jenkins on 27 Jul 2009 at 06:11 pm