How to reorder SharePoint list fields programmatically

In a SharePoint list, when you enable “Allow management of content types”, you change the order of the fields through the UI. This will affect the order of the fields in forms and when viewing a list item. If you want to do this programmatically, however, Microsoft hasn’t provided a standard way of doing it through the object model. Nonetheless, you can achieve this with a RPC.

For a content type, you can change the order of its fields with the SPFieldLinkCollection.Reorder method. For lists, however, there is no similar method.

You need to do a RPC, such as in the following method, to reorder the fields of a SharePoint list programmatically:

public void ReorderFields(SPList list, string[] internalNames) {
    StringCollection fields = new StringCollection();
    fields.AddRange(internalNames);
    
    foreach (SPField field in list.Fields) {
        if (!fields.Contains(field.InternalName)) {
            fields.Add(field.InternalName);
        }
    }
    StringBuilder sb = new StringBuilder();
    XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
    xmlWriter.Formatting = Formatting.Indented;
    xmlWriter.WriteStartElement("Fields");
    
    for (int i = 0; i < fields.Count; i++) {
        xmlWriter.WriteStartElement("Field");
        xmlWriter.WriteAttributeString("Name", fields[i]);
        xmlWriter.WriteEndElement();
    }
    xmlWriter.WriteEndElement();
    xmlWriter.Flush();
    string rpcTemplate = @"<?xml version=""1.0"" encoding=""UTF-8""?>  
        <Method ID=""0,REORDERFIELDS"">  
        <SetList Scope=""Request"">{0}</SetList>  
        <SetVar Name=""Cmd"">REORDERFIELDS</SetVar>  
        <SetVar Name=""ReorderedFields"">{1}</SetVar>  
        <SetVar Name=""owshiddenversion"">{2}</SetVar>  
        </Method>";
    string rpcCall = string.Format(
        rpcTemplate,
        list.ID,
        SPHttpUtility.HtmlEncode(sb.ToString()),
        list.Version);
    list.ParentWeb.AllowUnsafeUpdates = true;
    list.ParentWeb.ProcessBatchData(rpcCall);
    list.ParentWeb.AllowUnsafeUpdates = false;
}

The first parameter is the list instance and the second an array of strings with the internal names of the fields by their desired order.

The method will then add any missing fields from the list to the collection. After that it will build the CAML for the reorder fields command. In the end it will execute the command through the ProcessBatchData method of the parent web of the list.

Nuno Freitas
Posted by Nuno Freitas on September 23, 2013

Related articles