Ryan Ramcharan

Office Developers Unite
posts - 3, comments - 1, trackbacks - 0

Setting Enable Audience Targeting Programmatically

Someone recently posted on the MSDN SharePoint Forum a question on how to programmatically enable audience targeting on a list.

 

I thought to myself, well this should be easy enough, must be a property on the SPList.  So off to MSDN to check out the members of SPList.  Scrolled down, up and then down again, and could not find anything.  Okay, I'll hit Ctrl+F and search for it.  No luck either.  So, the next thing to do was figure out what exactly does this setting do.  Well if we enable it, and take a look at the settings for the list, we will see that it adds a new column to the list called Target Audiences of type Audience Targeting

This type is actually added to the existing list content type, so now we just need to figure out what the ID and Type of the field is and we are in business.  With the help of a small console application we can see the ID and type of field. 

Now it's just a matter of inserting that field into the list with the code below and presto, we have just enabled audience targeting functionality on our list programmatically!

public void AddTargetAudienceField()
{
     SPList currentList = SPContext.Current.List;
     // Create the field XML that will be added to the list
     XmlElement fldElement = new XmlDocument().CreateElement("Field");
     fldElement.SetAttribute("ID", "61cbb965-1e04-4273-b658-eedaa662f48d");
     fldElement.SetAttribute("Type", "TargetTo");
     fldElement.SetAttribute("Name", "TargetTo");
     fldElement.SetAttribute("DisplayName", "Target Audiences");
     fldElement.SetAttribute("Required", "FALSE");
     // Add the field XML and update the list
     currentList.Fields.AddFieldAsXml(fldElement.OuterXml);
     currentList.Update();
}

Print | posted on Sunday, February 24, 2008 10:23 PM |

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 4 and 6 and type the answer here:

Powered by: