Question

I have to add a choice field (dropdown) to a sharepoint list. I'm using the SharePoint API in Visual Studio.

Here is me code. I have tried to run this and there are no errors but it doesn't work.

private void addChoiceField(SPFeatureReceiverProperties properties, String _listName, String _fieldName)
        {
            using (SPWeb _web = properties.Feature.Parent as SPWeb)
            {
                    SPList _list = _web.Lists.TryGetList(_listName);
                    writeLog(properties, "list name:" + _listName);
                    SPFieldChoice _fieldDD = (SPFieldChoice)_list.Fields[_fieldName];
                    writeLog(properties, "fieldname:" + _fieldName);
                    if (_fieldName == "State")
                    {
                        _fieldDD.Choices.Clear();
                        _fieldDD.Choices.Add("Gesloten-Verloren");
                        _fieldDD.Choices.Add("Analyse nodig");
                        _fieldDD.Choices.Add("Onderhandeling of revise");
                        _fieldDD.Choices.Add("Presentatie of demo");
                        _fieldDD.Choices.Add("Voorstel voor prijsofferte");
                        _fieldDD.Choices.Add("Prospect");
                        _fieldDD.Choices.Add("Waardevol");
                        _fieldDD.Choices.Add("Gesloten-Gewonnen");
                        _fieldDD.Update();
                    }
}
}

Does anyone knows what's wrong or how to add a choicefield in a different way using the API?

Was it helpful?

Solution

You need to call

_list.Fields.CreateNewField

to actually add it to the list instead of trying to pull an existing field from the list.

Here is a link to the method description: http://msdn.microsoft.com/en-us/library/microsoft.harepoint.spfieldcollection.createnewfield.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top