in

SharePoint Blogs

The Best Place for SharePoint-related Blogs

Ton Stegeman [MVP] weblog

I have moved my blog to http://www.tonstegeman.com/blog. If you have a blogpost at sharepointblogs that does not display all the content on the right hand side, please go to the new blog. It has all the posts that are on this blog as well. I you have any feedback, please send me a message through the contact form.

Adding an item of a specific contenttype to a list

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”.

Comments

No Comments

Need SharePoint Training? Attend a SharePoint Bootcamp!

Posts (c) their respective authors. Everything else (c) 2007 SharePoint Experts