Adding / Modifying Choices in a SharePoint Choice Field programmatically using the Client Object Model

The SharePoint 2010 Client Object Model isn’t the best documented thing in the world, but it sure does make some tasks a lot easier (without requiring execution on the sharepoint server itself)

I needed to add an option to a dropdown list in a bunch of document libraries. Here’s how:

...
using sp = Microsoft.SharePoint.Client;
...
        private void AddChoicesToField()
        {
            using (sp.ClientContext cxt = new sp.ClientContext("http://sharepointserver"))
            {
                //Basic code to load the list
                sp.Web myWeb = cxt.Site.OpenWeb("http://sharepointserver/sitename");
                cxt.Load(myWeb);
                sp.List myList = myWeb.Lists.GetByTitle("MyListName");
                cxt.Load(myList);
                //The field must be cast to a FieldChoice using context.CastTo
                sp.FieldChoice myField = cxt.CastTo<sp.FieldChoice>(myList.Fields.GetByInternalNameOrTitle("My Field Name"));
                cxt.Load(myField);
                cxt.ExecuteQuery();
                //Copy the choices to a string list
                List<string> OptionList = new List<string>(myField.Choices);
                //Add whatever new values you want to the list
                OptionList.Add("New Value");
                //Convert the list to a string array and assign it to the Choices parameter
                myField.Choices = OptionList.ToArray();
                myField.Update();
                cxt.ExecuteQuery();
            }
        }

Make sure your project has a reference to Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.Runtime.

Leave a Reply