Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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.

share|improve this question
    
Thanks for your flag, but can you edit your post to avoid any possible confusion? Many thanks. - mod –  SPDoctor Oct 2 '12 at 18:33
add comment

2 Answers

up vote 2 down vote accepted

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");
share|improve this answer
    
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? –  DeeMac Oct 2 '12 at 15:09
1  
Umm - need more info - can you add the caml from the field declaration to the question? –  SPArchaeologist Oct 2 '12 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? –  DeeMac Oct 2 '12 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. –  DeeMac Oct 2 '12 at 17:01
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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