This post will detail you with sample code snippet to update and clear value of a taxonomy field of a list item.
Update value to Taxonomy Field:
public void UpdateTaxonomyField(ClientContext ctx, List list,ListItem listItem,string fieldName,string fieldValue) { Field field = list.Fields.GetByInternalNameOrTitle(fieldName); TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field); TaxonomyFieldValue termValue = new TaxonomyFieldValue(); string[] term = fieldValue.Split('|'); termValue.Label = term[0]; termValue.TermGuid = term[1]; termValue.WssId = -1; txField.SetFieldValueByValue(listItem, termValue); listItem.Update(); ctx.Load(listItem); ctx.ExecuteQuery(); }
Here make sure you pass the term to be updated in the format termname|guid.
Note: This is just one of the methods using which you can update the Taxonomy field value. There are other methods such as :
TaxonomyFieldValue.SetFieldValueByTerm : Here just the parameters are different.
txField.SetFieldValueByTerm(listItem,termObj,lcid); // Here termObj is an object of Term. lcid is the language code identifier (LCID) of the language of the default Label to use.
Clearing Value of a Taxonomy Field:
Interestingly to set the value of a Taxonomy Field there are a lot of methods available , but none of those methods work if you want to clear the value. The only one which actually works is TaxonomyField.ValidateSetValue method.
public void ClearTaxonomyFieldValue(ClientContext ctx, List list, ListItem listItem, string fieldName)
{
Field field = list.Fields.GetByInternalNameOrTitle(fieldName);
TaxonomyField txField = clientContext.CastTo(field);
txField.ValidateSetValue(listItem, null);
listItem.Update();
ctx.Load(listItem);
ctx.ExecuteQuery();
}
Hope this post saves your time 🙂
Leave a Reply to Unnikannan Ayilliath Cancel reply