5

I'm trying to get the selected value of a dropdown list item. Nothing works.

SPFieldChoice dropdown = list.Fields["Admin Guide"] as SPFieldChoice;
var choices = dropdown.Choices;
var selection = dropdown.GetFieldValueAsText(choices).ToString();

Also tried:

SPFieldChoice dropdown = list.Fields["Admin Guide"] as SPFieldChoice;
string selection = dropdown.GetFieldValueAsText(item["Admin Guide"]);

Tried other options as well, but nothing will grab the currently selected item.

Please help.

  • It would be great if someone could provide working production code how to get the selected value. – psdpainter Jun 6 '14 at 18:02
  • 2
    Shouldn't you be trying to access the properties of the item that triggered the event and not be trying to access the list column? – Eric Alexander Jun 6 '14 at 18:30
  • Yes...I'm storing them as SPListItem item = properties.ListItem; – psdpainter Jun 6 '14 at 18:35
10

The only way I could get the selected value of a dropdown choice column was with the following:

SPFieldChoice dropdown = item.Fields.GetFieldByInternalName("AdminGuide") as SPFieldChoice;
string selectedValue = dropdown.GetFieldValueAsText(item["AdminGuide"]);

Thanks RJ and PirateEric for your comments!

1

I just wrote a test case to validate this, and your second set of code is correct as long as this is a single value choice field (a dropdown) and not a multiple value choice field.

  • That doesn't work. "Cannot apply indexing with [] to an expression of type Microsoft.SharePoint.SPList." – psdpainter Jun 6 '14 at 17:40
  • I'm not sure what problem you're facing, but I've updated my answer. Are you getting an error? If not, how was this column created? – RJ Cuthbertson Jun 6 '14 at 17:57
  • Yes, it's a regular Choice column as dropdown. It was created server side. I've tried adding this code to ItemAdded, ItemAdding, ItemUpdating, ItemUpdated events...all with no success. Every time the value returns null. The latest error reads: Unable to cast object of type 'Microsoft.SharePoint.SPFieldChoice' to type 'System.String'. – psdpainter Jun 6 '14 at 18:01
  • Maybe more context would help, because the code in your question doesn't ever cast an SPFieldChoice to a string... – RJ Cuthbertson Jun 6 '14 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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