1

I'm attempting to create a feature stapled solution that pushes out custom branding to every new site collection created. The following code is in my event receiver:

    public override void FeatureActivated(SPFeatureReceiverProperties properties)
    {
        using(SPSite sitecollection = properties.Feature.Parent as SPSite)
        {
            using (SPWeb site = sitecollection.OpenWeb())
            {
                foreach (SPWeb web in sitecollection.AllWebs)
                {
                    try
                    {
                        SPList list = web.Lists.TryGetList("Composed Looks");
                        foreach (SPListItem item in list.Items)
                        {
                            if(item.Title != "Current" || item.Title != "Dynetics")
                            {
                                item.Delete();
                                item.Update();
                            }
                        }
                    }
                    finally
                    {
                        if(web != null)
                        {
                            web.Dispose();
                        }
                    }
                }
            }
        }
    }

But when deploying the solution I get the error:

Error occurred in deployment step 'Activate Features': Item does not exist. It may have been deleted by another user.

WHY??

1 Answer 1

2

By looking into your code, i think the problem is

item.Delete();
item.Update();

You are updating item after you are deleting, there is no need to update the item after delete.

You can not update a deleted item.

7
  • Ok that got rid of the original error, but now I receive: Collection was modified; enumeration operation may not execute.
    – psdpainter
    Commented May 28, 2014 at 17:08
  • use for (int i = items.Count - 1; i >= 0; i--) { SPListItem item = items[i]; item.Delete(); }
    – Aanchal
    Commented May 28, 2014 at 17:21
  • you are getting this error because You can not modify a collection while enumerating it because the iterator will reset and you will have exception.I
    – Aanchal
    Commented May 28, 2014 at 17:23
  • Or you can maintain a list of listitems to delete and delete them one by one after your foreach statement.
    – Aanchal
    Commented May 28, 2014 at 17:27
  • Tremendously helpful, Aanchal. Thank you very much. This solved the problem
    – psdpainter
    Commented May 28, 2014 at 17:33

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.