Question

I have a document library with a custom managed metadata field. I want to get the terms that are used for a particular item. I can get access to the item through the object model, and can get to the field (which by then the type is actually called a TaxonomyField), but I can't seem to get access to the terms for the field.

To be clear: I am not looking to get all possible terms for the field (I know how to do this, and there are a TON Of blogposts). I am trying to get to ONLY the terms that were picked by the user for a particular item.

Was it helpful?

Solution 2

This is how you do it

TaxonomyFieldValueCollection tfvc = (list.Items[0]["Field Name"] as TaxonomyFieldValueCollection);
var valuesList = (from v in tfvc select v.Label).ToList();

OTHER TIPS

@Ashish Patel answer does not actually work when i tried but i was able to figure it out a bit differently. Here is my version of the helper method based on example provided by code ninja blog, here:

private List<Guid> GetTermsIds(SPListItem listItem, string fieldName)
{
    var taxonomyField = listItem.Fields.GetFieldByInternalName(fieldName) as TaxonomyField;
    if (taxonomyField.AllowMultipleValues)
    {
        var fieldValuesCollection = listItem[taxonomyField.Title] as TaxonomyFieldValueCollection;
        return fieldValuesCollection.Select(x => new Guid(x.TermGuid)).ToList();
    }
    else
    {
        var fieldValue = listItem[taxonomyField.Title] as TaxonomyFieldValue;
        return new List<Guid>() { new Guid(fieldValue.TermGuid) };
    }
}

The AllowMultipleValues property can be accessed by casting the field column as an SPFieldLookup:

SPFieldLookup tagsField = (SPFieldLookup)listToQuery.Fields["your column name"];

You need to read them through TaxonomyFieldValueCollection or TaxonomyFieldValue class depending upon value of AllowMultipleValues. Shown below

if (tagsField.AllowMultipleValues)         
{             
    TaxonomyFieldValueCollection tagsValues = new TaxonomyFieldValueCollection(tagsField);             
}         
else         
{             
    TaxonomyFieldValue tagValue = new TaxonomyFieldValue(tagsField);             
}

Then check TaxonomyFieldValue's Label and TermGuid properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top