28 Dezember 2007

Get or set the content type of a list item programmatically

Keith asked my last week, how you can get the content type of a list item. It's quite easy:

First you have the get the Guid of the field "ContentType". With this Guid you can access the properties bag of an instance of a SPListItem. There the content type is stored as a string.
SPListItem item = ...
Guid fieldGuid = item.Fields.GetFieldByInternalName("ContentType").Id;
item[fieldGuid] = "Document";
item.Update();

1 Kommentar:

pshisbey hat gesagt…

Or you can use an SPContentTypeId object:

SPContentTypeId myCTID = new SPContentTypeId("guid of the target content type");

myListItem["Content Type ID"] = myCTID;

// or you could probably use the Id or Guid of the ListItem's content type field such as:

Guid oG = new Guid("guid of the listitem's content type field");

myListItem[oG] = myCTID;