7

I have a list that I want to add a choice field to programatically. I also want to specify the choices. Here is the code:

var fieldChoice = (SPFieldChoice)list.Fields.CreateNewField("Choice", "FieldName");
fieldChoice.Choices.Add("Choice 1");
fieldChoice.Choices.Add("Choice 2");
list.Update();
fieldChoice.Update();

I've been playing around with the placement of the list.Update() and fieldChoice.Update() lines, but nothing seems to work. If I leave out fieldChoice.Update(), the field does not have any choices. If I inlcude fieldChoice.Update(), I get this exception:

System.ArgumentException was unhandled by user code
  Message=<nativehr>0x80070057</nativehr><nativestack></nativestack>
  Source=""
  StackTrace:
       at Microsoft.SharePoint.Library.SPRequestInternalClass.UpdateField(String bstrUrl, String bstrListName, String bstrXML)
       at Microsoft.SharePoint.Library.SPRequest.UpdateField(String bstrUrl, String bstrListName, String bstrXML)
       at Microsoft.SharePoint.SPField.UpdateCore(Boolean bToggleSealed)
       at Operations.Layouts.Operations.Main.CreateList(SPWeb web, String listName)
       at Operations.Layouts.Operations.Main.Page_Load(Object sender, EventArgs e)
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at Microsoft.SharePoint.WebControls.UnsecuredLayoutsPageBase.OnLoad(EventArgs e)
       at Microsoft.SharePoint.WebControls.LayoutsPageBase.OnLoad(EventArgs e)
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException:

What am I doing wrong?

7

I believe with that technique you are creating a Field object for that list but it does not actually add a column, similar to adding columns to a Datatable().

For creating fields via code I typically go with

 //Add Column to list
 //GUID SPList.Fields.ADD(name,type,required);
 list.Fields.Add("Field Name", SPFieldType.Choice, false);

 //Get Field Reference
 SPFieldChoice col = (SPFieldChoice) list.Fields["Field Name"];

 col.Choices.Add("option 1");
 col.Choices.Add("option 2");
 col.DefaultValue = "option 1"; //otherwise blank row by default.

 col.update();  //Saves choices to column

 list.update();
  • The list update at the end is not necessary, the field update is enough. – Shihan Oct 5 '17 at 14:53
4

One hint is to use AddRange() method to add array of strings as choices instead of adding choices with Add() one by one

string[] Choices = { "choice1", "choice2", "choice3", "choice4", "choice5" };
col.Choices.AddRange(Choices);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.