Friday, February 18, 2011

How to reorder columns in Sharepoint Lists through Object model

Let's first see what are site columns, list columns and content types 

Site columns  
Site columns are those columns created at site level. These columns will be available across the site. We can add these columns to any list within the site. We can create the site columns by navigating to site columns gallery from site settings.

List columns
List columns are the columns to the list they are created. These columns cannot be added to other lists. If we want the same column to be added to some other list, we need to create a site column and then attached it to list or we need a new column to the list.

Content Types
Content types are nothing but group of columns. Content types created at site level are known as site content types. Content types created at list level are known as list content types.
Whenever we create a new Custom list, the content type “Item” gets attached to it. [For Doc library, content type “document” gets associated with it].

Whenever we add list columns to the list, those list columns will gets automatically associated with the existing content type(i.e.)”Item”. We might wonder that we did not explicitly create a content type, but how come it is getting associated. That’s the power of content type. You can see this behavior by enabling “Allow management of content type” in advanced settings of list settings. Then click on the item content type and have a look. Along with Title column you would be able to see the list columns associated with it. 


Now let’s see how we can re-order list columns through OM.
Upon knowing the fact that list columns gets automatically get associated with the content type, we are going to reorder the fields(columns) in the content type of the list. 

The code given below reorders the columns of a custom list.

Note: This changes the column order in new and edit form of the items in List. It does not change the order in display form. To achieve the column reordering in display form, you need to reorder columns in views.

using (SPSite site = new SPSite("http://SiteURL/"))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPContentType ct = web.Lists["List_Name"].ContentTypes["Item"];
                    SPFieldLinkCollection flinks = ct.FieldLinks;

                    string[] fields = new string[3] { "firstCol", "Title", "secondCol" };
                    flinks.Reorder(fields);
                    ct.Update();
                }
            }


1 comment:

  1. Hi,
    Thanks for sharing info.

    Re-Order the sharepoint site content type columns using powershell script:

    http://sharepointquicksolutions.blogspot.in/2014/12/reoreder-sp-content-types-columns.html

    Regards,
    Sasi Kumar Reddy
    http://sharepointquicksolutions.blogspot.in/

    ReplyDelete