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?