Stumbles and Travels


Programmatically Creating a Content Type and Site Column
August 18, 2007, 3:43 pm
Filed under: MOSS

In this post I show how you can create a content type programmatically and then create a new site column and add it to your new content type.

using(SPSite site = new SPSite(urlToSite))
{
   using(SPWeb web = site.OpenWeb())
   {
      SPContentType contentType =
         new SPContentType(web.AvailableContentTypes["Parent Name"],
         web.ContentTypes, “Name”);

      // use true below to make required field
      web.Fields.Add(“NameOfColumn”, SPFieldType.TypeOfField, true);
      SPFieldLink fieldLink = new SPFieldLink(web.Fields["NameOfColumn"]);
      contentType.FieldLinks.Add(fieldLink);
      contentType.Update();
   }
}