Recently, I got a question from a developer who was wondering why the following statement caused a System.NullReferenceException:

SPContentType itemContentType = myCustomList.ContentTypes[SPBuiltInContentTypeId.Item];

The SPBuiltinContentTypeId Class contains static readonly fields representing all out-of-the-box ContentTypes in SharePoint Foundation (or WSS). The thing here is that when a Content Type is assigned to a List by using “Add from existing site content types” there actually is a new ContentType being generated under the hood. This newly generated ContentType actually inherits from the ContentType you selected to assign so it (initially) behaves exactly the same as it’s parent but it will have it’s own unique ID.

The SPBuiltInContentTypeId Class’ fields represent only the SPContentTypeIds of the ContentTypes typically instantiated at SiteCollection scope. Referencing a List-assigned version of the “same” ContentType won’t work using the overload of SPContentTypeCollection’s (SPList.ContentTypes) indexer taking a SPBuiltInContentTypeId because the ContentType has it’s own unique ID. In order to reference the List-scoped ContentType you should use one of the other two overloads of this class’ indexer instead. The first is taking an Int32 representing the index of a ContentType whithin the collection. However, for a more predictable result I’d recommend using the overload accepting a string representing a ContentType’s name:

SPContentType itemContentType = myCustomList.ContentTypes["Item"];

Categorieën: Nieuws
20 augustus 2010 Robert Jaakke

Another option is to use the BestMatch method of the SPContentTypeCollection. BestMatch: Searches the collection and returns the content type identifier (ID) that is the nearest match to the specified content type ID.

20 augustus 2010 Paul Pascha

Hi Robert, thanks for your reply! Indeed, that’s another and I think an even better / more convenient way to retrieve a List ContentType which I should have mentioned too…

23 oktober 2011 Wiskunde Bijles

Erg goed! Toch weer iets opgestoken. Ga je hier nog meer over plaatsen? Ik ben zeer verrast in ieder geval.

Geef een reactie

Jouw e-mailadres wordt niet gepubliceerd. Verplichte velden zijn gemarkeerd met *

*

De volgende HTML tags en attributen zijn toegestaan: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

  • Categories

  • Tags

  • Blog Authors

    Amy
    anita
    Anneke
    Danny Burlage
    Dennis Vendel
    Freek Berson
    Gerard
    Iris
    Jasper Oosterveld
    Jean-Claude Chan
    Jorn
    Lab Chicks
    Luc Joziasse
    Maarten van Noort
    Maarten Wijsman
    Marlon
    Martijn Bellaard
    Natasja van Doorn
    Paul Pascha
    Peter Heuvelman
    Rick Slager
    Robert van Son
    Roeland Jimenez
    SanderZ
    Sjoerd Schudde
    Stefan van der Wiele
    Tim Heuperman
    Wortell
  • Archief