Get Terms from the Field:
TaxonomyField commodityGrpFld = (TaxonomyField)web.Fields[“FieldName”];
// get the Term Store ID from the field
Guid commodityGrptermStoreId = commodityGrpFld.SspId;
// Open a taxonomysession and get the correct termstore
TaxonomySession session = new TaxonomySession(oSite);
TermStore termStore = session.TermStores[commodityGrptermStoreId];
#region get terms from commodity termset
try
{
TermSet termSetCommodity = termStore.GetTermSet(commodityGrpFld.TermSetId);
if (termSetCommodity != null)
{
TermCollection CommodityTermColl = termSetCommodity.Terms;
ArrayList commodityList = new ArrayList();
foreach (Term commTerm in CommodityTermColl)
{
commodityList.Add(commTerm.Name);
}
//binding to listbox
lbCommodityGrp.DataSource = commodityList;
lbCommodityGrp.DataBind();
}
}
catch (Exception)
{ }
#endregion
Update the Item value for Managed Metadata field:
TaxonomyField taxoField_Commodity =spfile.Item.Fields[[“FieldName”] as TaxonomyField;
TaxonomySession taxoSession = new TaxonomySession(oSite);
TermStore store = taxoSession.TermStores[taxoField_Commodity.SspId];
TermSet termSet = store.GetTermSet(taxoField_Commodity.TermSetId);
if (taxoField_Commodity.AllowMultipleValues)
{
TermCollection terms = termSet.GetAllTerms();
List<string> taxonomyValueList = new List<string>();
foreach (ListItem item in lbCommodityGrp.Items)
{
if (item.Selected)
{
taxonomyValueList.Add(item.Value);
}
}
TaxonomyFieldValueCollection fieldValues = new TaxonomyFieldValueCollection(taxoField_Commodity);
foreach (Term term in terms)
{
if (taxonomyValueList.Contains(term.Name))
{
TaxonomyFieldValue fieldValue = new TaxonomyFieldValue(taxoField_Commodity);
fieldValue.TermGuid = term.Id.ToString();
fieldValue.Label = term.Name;
fieldValues.Add(fieldValue);
}
}
taxoField_Commodity.SetFieldValue(spfile.Item, fieldValues);
}
Get the Item value for Managed Metadata field:
We need to convert the item value to TaxonomyFieldValueCollection