Add choices to SPFieldChoice programatically in a Sandboxed solution

The other day I stumbled upon a weird behavior when developing a sandboxed solution. I was trying to add choices programatically to an SPFieldChoice field using the object model. After hours trying to debug the problem, looking at the ULS logs etc. I learned that is actually a known bug. There is a workaround though, you can modify the xml schema of the field to modify/add your choices.


var category = (SPFieldChoice)rootWeb.Fields["Category"];
var choices = new[] { "category one", "category two"};

var doc = new XmlDocument();
doc.LoadXml(category.SchemaXml);
var fieldNode = doc.SelectSingleNode("/Field");
if (fieldNode != null)
{
    var choicesnode = doc.SelectSingleNode("/Field/CHOICES");
    if (choicesnode != null)
    {
        fieldNode.RemoveChild(choicesnode);
    }

    var choicesElement = doc.CreateElement("CHOICES");

    foreach (string choice in choices)
    {
       var choiceElement = doc.CreateElement("CHOICE");
       choiceElement.InnerText = choice;
       choicesElement.AppendChild(choiceElement);
    }

    fieldNode.AppendChild(choicesElement);
    category.SchemaXml = doc.OuterXml;
    category.Update(true);
 }

You have to love SharePoint

Leave a Reply

Your email address will not be published. Required fields are marked *