Friday, June 15, 2012

Programmaticlly Create Choice Field with Default Value in SharePoint


In this post i am explaining how to create a choice field in the list and set its default value pro-grammatically

First create a string collection of choice values that you want to use

  StringCollection _statusTypes = new StringCollection();
            _statusTypes.Add("Complete");
            _statusTypes.Add("Incomplete");

Get the field collection from the list and add new choice field to this


 SPList list = web.Lists[listname];
            SPFieldCollection _fields = list.Fields;


  _fields.Add("MyChoiceField", SPFieldType.Choice, true, false, _statusTypes);

Here "MyChoiceField" is the name of field with _statusTypes choice values.

Next to set the default value of the choice field use the code below

Get the choice field
        SPFieldChoice fieldChoice = (SPFieldChoice)list.Fields["MyChoiceField"];
Set its default value              
      fieldChoice.DefaultValue = "Incomplete";
Set the format dropdown or radio button            
      fieldChoice.EditFormat = SPChoiceFormatType.RadioButtons;
and update the field
      fieldChoice.Update();
Now deploy the solution and add new item in the list you will see the default value set for this choice field

No comments:

Post a Comment