mo.notono.us

Friday, December 04, 2009

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: , , , , ,

3 Comments:

  • properties.AfterProperties["ContentType"].ToString is null in afterproperties. This does not work!

    By Blogger 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 Blogger 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 Anonymous, at Wednesday, October 31, 2012 6:32:00 PM  

Post a Comment

Links to this post:

Create a Link

<< Home