As some of you may know, it is a real pain to try and get hold of an item’s properties in the ItemAdding or ItemAdded event, there are various blog posts describing the problems and possible solutions.
The one blog post that stands out for me is this one by Randy Williams -
It seems if you are using a List rather than a document library then you can use the AfterProperties[“Fieldname”] to get the value in both the ItemAdded/ItemAdding events.
With a document library however, it seems to be a different story – both the ListItem.Properties and AfterProperties collections return no value when queried with the fieldname e.g. AfterProperties[“My Field Name”]. I have even tried using the internal field name – “My_x0020_Field_x0020_Name” but this also returns a null reference exception.
Well today, I have had a bit of a breakthrough – rather than reading the value directly from the properties.ListItem or properties.AfterProperties you need to first create a new SPListItem and then read the value from that. See my previous and now working code below:
Previous (Non-Working) Code:
[code lang="csharp"](if properties.ListItem[“My Field”] != null)
string mystring = properties.ListItem[“My Field”].ToString();
The above code would always return a null reference exception when it first checked for the properties.ListItem[“My Field”] not being null.
[code lang="csharp"]SPListItem item = properties.ListItem;
(if item[“My Field”] != null)
string mystring = item[“My Field”].ToString();
I can only imagine that creating a new SPListItem and querying that retrieves all the values after the item has been added to the database – I am not really sure! All I can say is that it works well so I am going to use this method on all future event handlers.
Hope this helps someone!