|
This previous post shows how you can create content types in code. The code in this post will show you how you add an item to a list and set the contenttype for that item. An SPItem object has a property called ContentType, but you cannot use that, because it is readonly.
The code to do this looks like this:
SPSite site = new SPSite("http://myportal/testsite"); SPWeb web = site.OpenWeb(); SPList list = web.Lists["ContentTypeTest"]; // We first check if the contenttype is available and then use the id. SPContentType contentType = web.AvailableContentTypes["Proposal"]; if (contentType != null) { SPListItem item2 = list.Items.Add(); item2["ContentTypeId"] = contentType.Id; item2["Title"] = Custom contenttype, set from code!”; item2.Update(); }
First we open the site and get an SPList object of the list we want to add the item to. In my sample the list is called “ContentTypeTest”. The next step is to get an object of the SPContentType type from the available contenttypes for the web. If it exists, we can add an item to the list and set the value of the “ContentTypeId” field for our item. The contenttype in my sample is called “Proposal”. |