How to programmatically set a content type as default content type in a SharePoint 2013 List

Ashok Raja
 
Solutions Architect
August 25, 2013
 
Rate this article
 
Views
2063

Use the bellow code to set a content type as a default content type for a SharePoint List. This code simply re-orders the sequence of content type by removing it the from the current index and inserting it again as the first element. This code does not removes or re-attaches the content type from the list, it simply changes the order of content type sequence.

Code

 private void SetDefaultContentType(SPList list, string ContenTypeName)
 {
     IList<SPContentType> cTypes = new List<SPContentType>();
     SPFolder root = list.RootFolder;
     cTypes = root.ContentTypeOrder;
     SPContentType cType = cTypes.SingleOrDefault(hd => hd.Name == ContenTypeName);
     int j = cTypes.IndexOf(cType);
     cTypes.RemoveAt(j);
     cTypes.Insert(0, cType);
     root.UniqueContentTypeOrder = cTypes;
     root.Update();
 }

How to Use

 using (SPSite site = new SPSite("[Server URL]"))
 {
     using (SPWeb web = site.OpenWeb())
     {
         SPList list = web.Lists["Your List Name"];
         SetDefaultContentType(list, "Your Content Type Name");
 
     }
 }
Category : Tips

Author Info

Ashok Raja
 
Solutions Architect
 
Rate this article
 
I am Ashok Raja, Share Point Consultant and Architect based out of Chennai, India. ...read more
 

Leave a comment