Thursday, April 15, 2010

SP 2010 - Creating ListItems with Managed Metadata Columns

Today I needed to create some list items programatically for a list that contained Managed Metadata columns. Since Managed Metadata columns are specialized SPLookups under the covers, it's a little more difficult to set your field value than just assigning the text value of your Term.

Here is a method that will set the value for you, and an example of how to use it. Note that in my example the Managed Metadata column is multi-value, even though the example method is only set up to add a single Term. If you have a single-value Managed Metadata column, you can leave out the TaxonomyFieldValueCollection.

class Program
 static void Main(string[] args)
  using (SPSite site = new SPSite("http://mysite"))
   SPList pl = site.RootWeb.Lists["MyList"];
   if (pl != null)
    TaxonomySession session = new TaxonomySession(site);
    TermStore termStore = session.TermStores["Managed Metadata Service"];
    Group group = termStore.Groups["MyGroup"];
    TermSet termSet = group.TermSets["MyTermSet"];

    SPListItem li = pl.AddItem();
    li[SPBuiltInFieldId.Title] = "my new item";

    Term term = termSet.Terms["MyTerm"];
    UpdateListItemTermColumn(li, "MyMetadataField", term);


 static void UpdateListItemTermColumn(SPListItem li, string fieldName, Term term)
  SPField termField = li.Fields[fieldName];

  TaxonomyFieldValueCollection tfvc = new TaxonomyFieldValueCollection(termField);
  tfvc.Add( new TaxonomyFieldValue(termField));
  li[fieldName] = tfvc;

  TaxonomyField taxonomyField = termField as TaxonomyField;
  if (taxonomyField != null)
   taxonomyField.SetFieldValue(li, term);

No comments:

Post a Comment