2

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.

1
  • Thanks for your flag, but can you edit your post to avoid any possible confusion? Many thanks. - mod
    – SPDoctor
    Commented Oct 2, 2012 at 18:33

2 Answers 2

3

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");
4
  • This worked (hence marked as answer) about 3 hours ago, now it does not!? "A look-up field contains invalid data. Please check the value and try again." By the way - in this instance - GetFieldValue is returning a string - would it not be effectively the same to just assign the string "Choice1" directly? Commented Oct 2, 2012 at 15:09
  • 1
    Umm - need more info - can you add the caml from the field declaration to the question? Commented Oct 2, 2012 at 15:21
  • Not sure where I'd get CAML for the field declaration or what it's used for sorry. Is it used to define the field? Commented Oct 2, 2012 at 15:44
  • My problems were completely misplaced here. It was another column that was causing the issue. Thanks a lot for all of your input anyway. Commented Oct 2, 2012 at 17:01
1

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.