SharePoint: Adding choice fields programmatically

As I know I will forget this, and I couldn’t find any decent examples on the web to do this, the code below shows how to add a choice field programmatically to a SharePoint list (with populated choices). Note that the class will need to reference the Microsoft.SharePoint namespace.

SPWeb web = new SPSite("http://localhost/sites/demosite").OpenWeb();
web.Lists.Add("Test List", "Test list description", SPListTemplateType.GenericList);

web.Lists["Test List"].Fields.Add("ExampleChoiceField", SPFieldType.Choice, false);

SPFieldMultiChoice choice = (SPFieldMultiChoice)web.Lists["Test List"].Fields["ExampleChoiceField"];
choice.Choices.Add("hello");
choice.Choices.Add("world");
choice.Update();

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>