다음을 통해 공유


Updating an item using ItemUpdating, ItemUpdated or any event receiver in SharePoint 2007

When using the Event Receivers in SharePoint a common scenario is to update a property on the item the event was fired on.  I’ve heard of people running into this issue a few times and it’s not all that obvious what the proper way is to do this.  A general software development principle is to suspend or temporarily disable events from firing that you may trigger unintentionally from your code.  It is particularly difficult to do this yourself in an event receiver in SharePoint because you typically don’t have any context to work with.  It turns out there is actually a very simple way to accomplish this, but it’s not clearly documented in the places you would expect it.  The MSDN documentation on the ItemUpdated and ItemUpdating event make no mention of a method called DisableEventFiring.  It turns out that by calling this method at the beginning of your event receiver you can prevent yourself from getting into an infinite loop.  You do want to make sure to call EnableEventFiring when you are done however.  Here is some sample code:

    1: try
    2: {
    3:     this.DisableEventFiring();
    4:  
    5:     SPListItem item = properties.ListItem;
    6:     string imageUrl = string.Empty;
    7:     if (item["PublishingRollupImage"] != null)
    8:     {
    9:         imageUrl = ((Microsoft.SharePoint.Publishing.Fields.ImageFieldValue)(item["PublishingRollupImage"])).ImageUrl;
   10:         item["ThumbnailImageURL"] = imageUrl;
   11:         item.SystemUpdate();
   12:     }                
   13: }
   14: catch (Exception ex)
   15: {
   16:     Utilities.LogError(properties.ListItem.Web, ex);
   17: }
   18: finally
   19: {
   20:     this.EnableEventFiring();
   21: }