Get content Type order in C#
-
10-12-2019 - |
Question
I am building a web part that would be added to the bottom of every library view and would display the folder content types making it easy to create a new folder (rather than having to go to documents - new document and then select from a drop-down).
My first attempt used
foreach(SPContentType type in list.ContentTypes)
This works but it gives me the content types in some sort of default order that has nothing to do with the order I set in the New Document button.
My next attempt I used
SPFolder folder = web.GetFolder(Request.RawUrl);
foreach(SPContentType type in folder.ContentTypeOrder)
This also works but gives me the exact same order as the first attempt even though I have unique new button orders set for each folder type in the library.
So how do I get the order in which items appear on the new button?
Solution 2
I figured it out I was getting the folder object incorrectly. There may be a more elegant way to do this, but the following works:
SPFolder folder;
string rawUrl = Request.RawUrl;
string rootFolder;
if (rawUrl.Contains("RootFolder"))
{
int start = rawUrl.IndexOf("RootFolder");
int end = rawUrl.IndexOf("&", start);
int length = end - start;
rootFolder = rawUrl.Substring(start, length);
string url = rootFolder.Replace("RootFolder=", "");
folder = web.GetFolder(url);
}
else
{
folder = list.RootFolder;
}
foreach (SPContentType type in folder.ContentTypeOrder)
OTHER TIPS
In order to retrieve list of content types that ordered the same way as items appear on the new button:
SPFolder folder = list.RootFolder;
if (folder.ParentListId != Guid.Empty)
{
var contentTypeOrder = folder.ContentTypeOrder;
foreach (var contentType in contentTypeOrder)
{
//...
}
}
SPFolder.ContentTypeOrder property.
According to MSDN:
This property returns a list of SPContentType objects. The sequence of objects in the list determines the order in which content types are listed in the user interface, such as on a Sharepoint list’s New menu or on the List Settings page.