SharePoint Event Receivers + Inherited Documents + ItemUpdating
A while back I posted some info about using Event Receivers in SharePoint 2010 and a workaround to item values being null. Today, I needed to do something much more basic, and during an ItemUpdating event set the value of a column. I wrote the code that I knew would work - but, of course, it simply wouldn’t work. I did a spot of Googling about, and found the chaps at Tango Technology who had written a very simple solution to it. But - it wouldn’t work for me. I knew the event was firing - but no matter what I did, the new value just wouldn’t “take”.
Then it dawned on me. The column I was trying to update was actually on the content type that the document I was editing was inheriting from. Looking through the AfterProperties collection in debug mode, it quickly became clear that this column wasn’t available to me. It had no problem with me assigning a value to it - but clearly SharePoint doesn’t actually touch any of these properties during its ItemUpdating event - only the properties on the actual content type. Annoying.
So the solution was to move the update code to the ItemUpdated and grab a fresh copy of the item. I reused some of my code from last time:
public override void ItemUpdated(SPItemEventProperties properties) { try { listID = properties.ListId; itemID = properties.ListItem.UniqueId; SPList list = properties.Web.Lists[listID]; SPListItem item = list.Items[itemID]; // you need this line otherwise it'll go round in an infinite loop // you also need to cast your columns otherwise it'll compare the objects which will never be the same. if ((DateTime)item["MyDateField"] != (DateTime)item["Modified"]) { item["MyDateField"] = item["Modified"]; item.SystemUpdate(false); } } catch { } }
This will update the value of the column in the base content type.