Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Wednesday, November 30, 2011

How to programmatically set the content type while creating a list item

If you create a new list item using the API without setting the content type id you will create a new item using the default content type.  However if you want to create a new list item using a different content type you will need to set the Content Type ID field.
The example below creates a list item using a content type called "Log" in a list called "HistoryLog".
using (SPSite site = new SPSite("http://intranet/"))
{
  using (SPWeb rootWeb = site.OpenWeb())
  {
    SPList historyLog = rootWeb.GetListFromUrl("/lists/historylog/allitems.aspx");
    SPListItem item = historyLog.Items.Add();
    item["LogType"] = "Warning";
    item["LogMessage"] = "Message .....";

    // set the content type id
    item["Content Type ID"] = rootWeb.ContentTypes["Log"].Id;
    
    item.Update();
  }
}

No comments:

Post a Comment