SharePoint Event Handlers – Getting item properties in the ItemAdded event

15 05 2009

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 –

http://www.synergyonline.com/blog/blog-moss/Lists/Posts/Post.aspx?ID=25

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:

(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.

Working Code:

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! 🙂

Advertisements

Actions

Information

2 responses

25 05 2009
anil

cool post…

9 11 2010
bruce

Was this in the ItemAdded method?Bcos the properties.ListItem is null in itemadding..im having issues trying to set column values in a document library list such that they display when the document is added i.e populated already onscreen. Seems like the afterproperties doesnt contain the entries for the columns i need to set!!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: