Getting the ContentType from an ItemAdding Event Handler
Inside an event handler for an ItemAdded event, getting the List Item’s ContentType is as easy as
var contentType = properties.ListItem.ContentType;
However, for ItemAdding, properties.ListItem is null.
Luckily, the ContentType name and Id are part of the properties.AfterProperties collection – the following will work:
SPList list = properties.List; string contentTypeName = properties.AfterProperties["ContentType"].ToString(); SPContentType contentType = list.ContentTypes[contentTypeName]; SPFieldCollection fields = contentType.Fields;
Between the AfterProperties field values and the content type field collection, you typically have all that you need... Just remember to not depend on properties.ListItem.
Labels: c#, howto, microsoft, moss, sharepoint, SharePoint2010
properties.AfterProperties["ContentType"].ToString is null in afterproperties. This does not work!
By Clem, at Friday, October 12, 2012 9:39:00 AM
Clem, sorry it's not working for you. It did for me 3 years ago, can't say I have tried since.
By Oskar Austegard, at Friday, October 12, 2012 10:10:00 AM
Document Library and Picture Library have different rules...
Library BeforeProperties AfterProperties properties.ListItem
ItemAdding No value No value Null
ItemAdded No value No value New value
ItemUpdating Original value Changed value Original value
ItemUpdated Original value Changed value Changed value
ItemDeleting No value No value Original value
ItemDeleted No value No value Null
By Anonymous, at Wednesday, October 31, 2012 6:32:00 PM
This article is outdated. Whoever wrote it, must delete it before it wastes anymore time of others
By Oliman, at Tuesday, April 08, 2014 1:25:00 AM
Thanks Oliman for such an insightful comment. Your valuable time must most certainly not be wasted. Perhaps if you slow down a bit you would notice things like dates showing the post is 5 years old. But it's great to learn that Microsoft has moved on since then.
By Oskar Austegard, at Tuesday, April 08, 2014 7:32:00 PM
Here are some results captured from the immediate window while debugging...
'properties.ListItem' is null
- Custom Content Type Event Receiver in a Document Library (with the Document Set feature activated)
Hope this helps.
By Scheevel, at Friday, May 30, 2014 3:10:00 PM
Post a Comment