Why What When Where How

June 9, 2008

creating content types in sharepoint through code ( c#)

Filed under: Uncategorized — KarTic @ 5:03 am

The follwoing snippet helps create a content type dynamically using c# and the further create field types / custom columns  for teh same .Also the way to access already existant field links ,has been vividly explained by the code .

 

 
site=new Microsoft.SharePoint.SPSite(“your sharepoint site url“);

         SPWeb web = site.OpenWeb();         

 

 

    // Create new content type

    SPContentType documentContentType = web.AvailableContentTypes["Document"];

    SPContentType newContentType = new SPContentType(documentContentType, web.ContentTypes, “Vini”);

    web.ContentTypes.Add(newContentType);

    newContentType = web.ContentTypes[newContentType.Id];

 

//To Create a custom Column

            string newFieldName = web.Fields.Add(“Region”,SPFieldType.Choice, true);

            SPFieldChoice regionField = (SPFieldChoice)web.Fields[newFieldName];

            regionField.Choices.Add(“Asia”);

            regionField.Choices.Add(“China”);

            regionField.DefaultValue = “China”;

            regionField.Update();

 

//To Add the Custom Column to the ConTent Type

SPField regionField = web.AvailableFields["Region"];

    SPFieldLink fieldLink = new SPFieldLink(regionField);

    newContentType.FieldLinks.Add(fieldLink);

    newContentType.Update(true);

 

 

    // To Add an existing column to the Content Type

    SPField regionField1 = web.AvailableFields["Address"];

    SPFieldLink fieldLink1 = new SPFieldLink(regionField1);

    newContentType.FieldLinks.Add(fieldLink1);

    newContentType.Update(true);          

 

 

           

 

   SPList list = web.Lists["Document Library"];

   SPContentType documentContentType1 = web.AvailableContentTypes["Ton Document"];

    list.ContentTypesEnabled = true;

    list.ContentTypes.Add(documentContentType1);

 

Blog at WordPress.com.