SharePoint 2013 – Update/Clear Taxonomy Field Value using C# CSOM

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 🙂

3 thoughts on “SharePoint 2013 – Update/Clear Taxonomy Field Value using C# CSOM

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s