Content Type – Setting up default content type programmatically


Here’s the sample to add and set a new content type as a default content type to a document library in a SharePoint site.  Also this will hide the pervious default content type.

 

SPSite oSPSite = new SPSite(""); // Site URL
SPWeb oSPWeb = oSPSite.OpenWeb();
SPList list = oSPWeb.Lists["Shared Documents"];  // Name of the List
SPContentType newContentType2 = oSPWeb.ContentTypes["ContentType_Two"]; // ContentType Two’s name
list.ContentTypes.Add(newContentType2);
SPContentTypeCollection currentOrder = list.ContentTypes;
List<SPContentType> result = new List<SPContentType>();
foreach (SPContentType ct in currentOrder)
{
    if (ct.Name.Contains("ContentType_Two"))
    {
        result.Add(ct);
    }
}
list.RootFolder.UniqueContentTypeOrder = result;
list.RootFolder.Update();

Comments (6)

  1. okok says:

    this set the order but the drop down select the last uploaded documents content  type.. even if it is as list number  second or third

  2. Patil says:

    Hi,

    I really appreciate the post u uploaded i.e. the content type order. changing . this displays the the order the way whatever we set in Unique content type order  property. but i am having a problem is that.. When i upload a file then it select last uploaded files content type in  Content type drop down even if that contentTypeitem is second or third number in Content type drop down.  This not select first item.  U getting me.  it must select First item in content Type drop-down.

    My contents type are === Audio, video, Image and Document.

    Thanks in advance … please reply

  3. Just one thing to say says:

    Have you notice that your example doesnt work???

  4. ND says:

    Can this be done in a declarative way?

  5. kumar says:

    Thank you. it was very helpful and saved my time

  6. RG says:

    Thanks for the script, it saved me sometime :)