0

I have writen the following code that should delete some items from a list on the current site, but it must contain some error and it currently doesen't work as expected.

protected void Button3_Click(object sender, EventArgs e)
{
   SPWeb web = SPContext.Current.Web;
   SPListItemCollection listItems = web.Lists["Szczegoly"].Items;
   for (int i = 1; i <= listItems .Count; i++)
   {
       if(TextBox4.Text==listItems["Data"])
       {
            listItems.Delete(i);
       }
   }
}

1 Answer 1

2

Assuming there aren't any other error related to permission and such (which we cannot see without a proper stacktrace), I would suggest you to have a look at the sample on the msdn page for the Delete method.

SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists["List_Name"];
SPListItemCollection collListItems = oList.Items;

for (int intIndex = collListItems.Count - 1; intIndex > -1; intIndex--)
{
    if (Convert.ToInt32(collListItems[intIndex]["Field1_Name"]) < 70 ||
        collListItems[intIndex]["Field2_Name"].ToString() == "None")
    {
        collListItems.Delete(intIndex);
    }
}

As you can see the for cycle is done BACKWARDS. This because with each item deleted the collection will get shorter, and if you simply go from 0--->n-1 you will then experience problem with the collection index. Also notice that the cycle is from n-1 to 0, while you are using a for 1-->n, so you would receive a out of bound exception on the "last" item (that is, non accounting the collection shortening problem).

Other than that, the code should work. Can you have a look at the above and see if this resolve your problem?

0

Your Answer

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

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