Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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);
       }
   }
}
share|improve this question
add comment

1 Answer

up vote 1 down vote accepted

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?

share|improve this answer
    
Its working now great :) Yeach thanks :) –  Grzegorz Z Oct 30 '12 at 15:18
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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