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); li.Update(); } } } 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