Karine Bosch Programmatically provisioning a TaxonomyField of type TaxonomyFieldTypeMulti - eguimaraes/sharepoint GitHub Wiki

Original em https://karinebosch.wordpress.com/2013/12/19/programmatically-provisioning-a-taxonomyfield-of-type-taxonomyfieldtypemulti/

Programmatically provisioning a TaxonomyField of type TaxonomyFieldTypeMulti 1 Votes

I had a hard time finding out how I could save multiple terms to a field of TaxonomyFieldTypeMulti using the SharePoint server object model.

The following code worked out for me:

    private static void SetTaxonomyValue(SPListItem item, Term term, string fieldName)
    {
        if (term != null && item != null && item.Fields[fieldName] != null)
        {
            if (item.Fields[fieldName].TypeAsString == "TaxonomyFieldType")
            {
                TaxonomyField taxonomyField = item.Fields[fieldName] as TaxonomyField;
                TaxonomyFieldValue taxvalue = new TaxonomyFieldValue(taxonomyField);
                taxvalue.TermGuid = term.Id.ToString();
                taxvalue.Label = term.Name;
                item[fieldName] = taxvalue;
            }
            else if (item.Fields[fieldName].TypeAsString == "TaxonomyFieldTypeMulti")
            {
                TaxonomyField taxonomyField = item.Fields[fieldName] as TaxonomyField;
                TaxonomyFieldValueCollection taxvalues = 

item[fieldName] as TaxonomyFieldValueCollection; if (taxvalues == null) taxvalues = new TaxonomyFieldValueCollection(taxonomyField); TaxonomyFieldValue taxvalue = new TaxonomyFieldValue(taxonomyField); taxvalue.TermGuid = term.Id.ToString(); taxvalue.Label = term.Name; taxvalues.Add(taxvalue); item[fieldName] = taxvalues; } } }

When the taxonomy field is of type TaxonomyFieldTypeMulti, terms are stored as a TaxonomyFieldValueCollection. The trick is that you first have to test whether you already have a term available in the collection or not. If not, you have to initialize the collection, otherwise you will get a “null reference” exception when you try to add a term to the collection.