Update Choice Field using CSOM (Client-side Object Model)

 I was putting together some CSOM Managed code to update an existing Choice column in SharePoint. Noticed that existing online examples show creating a new column or reading the values in a column, but nothing about update. The Red Herring that is the SchemaXml property on Field sent me the wrong way for a few minutes. Finally realized that by using the CastTo method on the context I could get a FieldChoice instance rather than just a Field. Once you have that the Choices are defined as a string array so very easy to update or replace. Here's the code;

 

using (ClientContext ctx = new ClientContext("http://MyServer/MySite"))

            {

                Field genericField = ctx.Web.Lists.GetById(listID).Fields.GetById(fieldGuid);

                FieldChoice fldChoice = ctx.CastTo<FieldChoice>(genericField);

                ctx.Load(genericField);

                fldChoice.Choices = “MyChoice1;MyChoice2;MyChoice3”.Split(";".ToCharArray());

                fldChoice.Update();

                ctx.ExecuteQuery();               

 

            }

Disclaimer: The software, source code and guidance on this website is provided "AS IS"
with no warranties of any kind. The entire risk arising out of the use or
performance of the software and source code is with you.

Any views expressed in this blog are those of the individual and may not necessarily reflect the views of any organization the individual may be affiliated with.