How to Add Choices to Existing Choice Field Using CSOM in SharePoint 2013 Online
In this blog you will see how to add choices to existing choice field using CSOM in SharePoint 2013 Online.
Code Snippet
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Security;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.SharePoint.Client;
-
- namespace CSOMOffice365
- {
- class Program
- {
- static void Main(string[] args)
- {
-
- string userName = "[email protected]";
-
- Console.WriteLine("Enter your password.");
- SecureString password = GetPassword();
-
-
-
-
- using (var clientContext = new ClientContext("https://c986.sharepoint.com"))
- {
-
-
- clientContext.Credentials = new SharePointOnlineCredentials(userName, password);
-
-
- Web web = clientContext.Web;
-
-
- List list = web.Lists.GetByTitle("Custom");
-
-
- Field field = list.Fields.GetByTitle("Choice");
- FieldChoice fieldChoice = clientContext.CastTo<FieldChoice>(field);
- clientContext.Load(fieldChoice);
-
-
- clientContext.ExecuteQuery();
-
-
- List<string> options = new List<string>(fieldChoice.Choices);
- options.Add("Option1");
- options.Add("Option2");
- options.Add("Option3");
- fieldChoice.Choices = options.ToArray();
-
-
- fieldChoice.Update();
-
-
- clientContext.ExecuteQuery();
-
-
- foreach (string option in fieldChoice.Choices)
- {
- Console.WriteLine(option);
- }
- Console.ReadLine();
- }
-
- }
-
- private static SecureString GetPassword()
- {
- ConsoleKeyInfo info;
-
-
- SecureString securePassword = new SecureString();
- do
- {
- info = Console.ReadKey(true);
- if (info.Key != ConsoleKey.Enter)
- {
- securePassword.AppendChar(info.KeyChar);
- }
- }
- while (info.Key != ConsoleKey.Enter);
- return securePassword;
- }
- }
- }
Output