SharePoint Internals – Hristo Pavlov’s Blog

7 August, 2008

Changing the default list content type programatically

This is something I wanted to do today and couldn’t find any obvious way to accomplish it. Checking the code behind of the ChangeContentTypeOrder.aspx page revealed how it can be done. You need to build a SPContentType[] array or List<SPContentType> list that contains the content types in the order you like. The first content type in the list will be used as a default content type for the SPList. Once you have the array/list you need to assign it to the SPFolder.UniqueContentTypeOrder member of the RootFolder of the list and then call SPFolder.Update() to apply your new order.

You cannot use any content types that inherit from one of these two content types:

SPBuiltInContentTypeId.Folder – 0x0120

SPBuiltInContentTypeId.UntypedDocument0x010104

The dummy example below reverses the order of the content types of a list and also uses another cool thing I learned from checking the code behind of the ChangeContentTypeOrder.aspx page – the cool .NET sorting method Array.Sort<TKey, TValue> that sorts two arrays simultaneously based on the first array. Of course I could have also used Array.Reverse() method to do the same.

SPContentType[] newContentTypeOrderArray = new SPContentType[list.RootFolder.ContentTypeOrder.Count];

int[] newContentTypeOrderIndexes = new int[list.RootFolder.ContentTypeOrder.Count];

 

for (int i = 0; i < list.RootFolder.ContentTypeOrder.Count; i++)

{

    newContentTypeOrderArray[i] = list.RootFolder.ContentTypeOrder[i];

    newContentTypeOrderIndexes[i] = -i;

}

 

Array.Sort<int, SPContentType>(newContentTypeOrderIndexes, newContentTypeOrderArray);

 

list.RootFolder.UniqueContentTypeOrder = newContentTypeOrderArray;

list.RootFolder.Update();

As mentioned above you should be also aware that the “Folder” and “Untyped Document” content types are not shown on the “Change New Button Order and Default Content Type” page however they may become a default content type of the list if you delete all other content types or make one of them default content type programmatically. In this situation if the default content type is “Folder” for example and you upload a file to the document library the file’s content type will be “Folder” – probably not something you really wanted to happen 🙂

Finally if you delete the “Folder” content type from a list you may experience some other strange things. See my EditForm Not Shown When Uploading a File post for details.

Create a free website or blog at WordPress.com.