How To Update Each Item In A SharePoint List Or Document Library When A Feature Is Activated



TODO:

Have you ever created an Event Receiver, and you would like to have it fire for all items in a list?  To do this, I created a Feature, that upon activation, will open a list or document library, and call Update() on each item in the list.  That will cause the Event Receiver to fire, thus applying its logic to each item in the list.

 

SOLUTION:

/// <summary>
/// Feature activated method
/// </summary>
/// <param name="properties"></param>
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
       try
       {
           //check the context
           if (SPContext.Current == null || SPContext.Current.Web == null || string.IsNullOrEmpty(SPContext.Current.Web.Url))
               return;

           // Use using to make sure resources are released properly  
           using (SPSite mysiteCollection = new SPSite(SPContext.Current.Web.Url))
           {
               // Alternately you can use oSite.RootWeb if you want to access the main site  
               SPWebInfo webinfo = mysiteCollection.AllWebs.WebsInfo.Find(delegate(SPWebInfo w) { return w.Title == "My Site Name"; });  //get the site by title (need to because name could be site/site)
               SPWeb rootSite = mysiteCollection.AllWebs[webinfo.Id];  //now get the web by GUID
                    
               SPList oList = rootSite.Lists["My List Name"];         //the list by display name
               foreach (SPListItem oItem in InputList.Items)
               {
                     //now just update it, so the event reciever fires
                     oItem.Update();
               }
           }
       }
       catch (Exception x)
       {   
       }
 }

 

NOTES:

There are no notes on this topic

 



Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading