Retrieving the Source Term for an items field.

[Important News!]

binarywaste - profile picture - 1000x1000

I’ve kicked off a new project/band where I’m creating music with a heavier techno/metal sound called binarywaste.  You should check it out by clicking right here!

I’m working on a project where I needed to get back to the term properties for various fields of a SPListItem that are based on a managed metadata column.

The actual process of getting back to a fields source term turned out to be rather simple, as the TaxonomyFieldValue object gives you everything you need.

I thought others might find this useful, so I present my GetTerm method here. This sample is provided as an Extension method, but you certainly can use it standalone if you wish.

using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;

namespace krichie.ExtensionMethods
  public static class Extensions
    /// <summary>
    /// Retrieves the Source Term for an items field.
    /// </summary>
    /// <param name="item" />The item to inspect</param>
    /// <param name="fieldName" />The name of the field</param>
    /// <returns>The Taxonomy term</returns>
    public static Term GetTerm(this SPListItem item, string fieldName)
      Term term = null;
      TaxonomyField field = item.Fields[fieldName] as TaxonomyField;

      // if this is not a TaxonomyField throw a new exception
      if (field == null)
        throw new Exception(fieldName
          + " is not of type"
          + " Microsoft.SharePoint.Taxonomy.TaxonomyField.");

      TaxonomyFieldValue value = item[fieldName] as TaxonomyFieldValue;
      if (value != null)
        TaxonomySession session =
          new TaxonomySession(item.ParentList.ParentWeb.Site);
        if (session.TermStores.Count != 0)
          TermStore store = session.TermStores[field.SspId];
          TermSet set = store.GetTermSet(field.TermSetId);
          // Get the term using the distinct TermGuid.
          // If you were to just use set.Terms[fieldName],
          // you would only examine the root of the term set.
          term = set.GetTerm(new Guid(value.TermGuid));
      return term;


– Keith

2 Replies to “Retrieving the Source Term for an items field.”

  1. Useful code.

    Most of the time I am getting null in this line of code
    TaxonomyFieldValue value = item[fieldName] as TaxonomyFieldValue

    is there any common reasons I am missing…

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: