Question

My apologies for asking, what seems like, a really basic question - but I can't appear to assign a value to a 'Choice' field programmatically and can't find anything documented anywhere.

Defined in my xml as:

 <Field Type="Choice" DisplayName="MyChoiceField" StaticName="MyChoiceField" Name="MyChoiceField"
       ID="[GUID]" Format="Dropdown" FillInChoice="FALSE" Required="FALSE" EnforceUniqueValues="FALSE" Indexed="FALSE"  >
    <Default></Default>
    <CHOICES>
      <CHOICE>Choice1</CHOICE>
      <CHOICE>Choice2</CHOICE>
    </CHOICES>
  </Field>

And my attempted assign as:

item["MyChoiceField"] = "Choice1";

But I'm getting the exception that this is an invalid value for a choice field.

Was it helpful?

Solution

You can use the GetFieldValue method of the field class if you are unsure of the actual type of the underling value.

For example:

item["MyChoiceField"] = listIstance.Fields["MyChoiceField"].GetFieldValue("Choice1");

OTHER TIPS

maybe somthing like this?

// Get a reference to the field.
SPFieldMultiChoice choiceField = (SPFieldMultiChoice)list.Fields.GetField(fieldInternalName);

// Create a field value with all choices selected.
// (A CheckBoxChoiceField control would have all boxes checked.)
SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue();
foreach (string choice in choices)
{
   values.Add(choice);
}

// Add an item to the list.
SPListItem item = list.Items.Add();
item[SPBuiltInFieldId.Title] = "Test item";
item[choiceField.Id] = values;
item.Update();

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spfieldmultichoicevalue.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top