Write value to a Target Audience Field Programmatically

Recently I came across an interesting question where user wanted to set the Target Audience Field value programmatically.

When setting this value through SharePoint UI you can either use your Audience which you have created using CA or you can use your SharePoint group.

So if you want to set Audience field value with the SharePoint Group using code it is very simple.​

In the following example I have enabled a list to have audience targetting. Doing this will add a field “Target Audience” to the list. Using the code I am updating the field value.

        private void setAudienceField()
{
SPWeb web = SPContext.Current.Web;;
SPList list = SiteWeb.Lists["YOUR LIST"];
web.AllowUnsafeUpdates = true;

SPGroup group = web.SiteGroups["YOUR SHAREPOINT GROUP NAME"];

SPListItem lstItem = list.Items.Add();

// set your list field values

............
// set Audience field
lstItem[lstItem.Fields["Target Audiences"].InternalName] = group.LoginName;

lstITem.Update();
web.AllowUnsafeUpdates = false;
}

If you want to update the audience field value with the audience name then the code is little different

        private void setAudienceField()
        {
                SPSite site = SPContext.Current.Site;
                SPWeb web = SPContext.Current.Web;
               SPList list = SiteWeb.Lists["YOUR LIST"];
               web.AllowUnsafeUpdates = true;

               Audience myAudience;

               SPServiceContext context = SPServiceContext.GetContext(site);

               AudienceManager audienceMgr = new AudienceManager(context);

               myAudience = audienceMgr.GetAudience("YOUR AUDIENCE NAME");

               SPListItem lstItem = list.Items.Add();

                 // set your list field values

                ............
                // set Audience field
               lstItem[lstItem.Fields["Target Audiences"].InternalName] = myAudience.AudienceID.ToString();
           
                itemToAdd.Update();
                web.AllowUnsafeUpdates = false;
        }