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

6 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  

  • This article is outdated. Whoever wrote it, must delete it before it wastes anymore time of others

    By Blogger 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 Blogger Oskar Austegard, at Tuesday, April 08, 2014 7:32:00 PM  

  • Here are some results captured from the immediate window while debugging...

    ? properties.ListItem.ContentType
    'properties.ListItem' is null

    ? properties.AfterProperties["ContentTypeId"]
    "0x0120D520003BBF99EB54C34597ACF700732E3882F600AA09EB683FFEB74BA408BE00002EB8DE"

    ? properties.AfterProperties["HTML_x0020_File_x0020_Type"]
    "SharePoint.DocumentSet"

    -override ItemAdding
    -SP 2010
    - Custom Content Type Event Receiver in a Document Library (with the Document Set feature activated)
    Hope this helps.

    By Blogger Scheevel, at Friday, May 30, 2014 3:10:00 PM  

Post a Comment

<< Home