The community for Microsoft Office SharePoint Server champions!

Determining if a SPContentType exists on a list by using its SPContentTypeId

How to check if a content type exists on a list by using the SPContentTypeId? Use the BestMatch() method of the SPContentTypeCollection.

Using the indexer is not straight forward because when the content type is assigned to a list, the SPContentTypeId is unique for that list. In other words, the following will return null even if myLibrary has the XMLDocument content type associated with it:

SPContentType t = myLibrary.ContentTypes[SPBuiltInContentTypeId.XMLDocument];

The unique ID of the content type associated to the list is a child of the content type ID found in SPWeb.AvailableContentTypes, therefore the following is a solution:

if(myLibrary.ContentTypes.BestMatch(SPBuiltInContentTypeId.XMLDocument).Parent == SPBuiltInContentTypeId.XMLDocument)
alreadyExists = true;

BestMatch() appears to always find a SPContentTypeId to return, and if the match is a direct descendent of the SPContentTypeId you are interested in, then the content type exists on the list.

This is preferable to using the friendly name of the content type in the SPContentTypeCollection indexer as the name may be localized.

Published Tuesday, 18 September 2007 9:18 PM by james

Comments

No Comments
Anonymous comments are disabled