Friday, February 4, 2011

Programmatically retrieving discussion list items

I spent the entire day yesterday, trying to figure out how to programmatically retrieve discussion lists. While this is still work in progress, here's some sample code that can help you do this.

using (SPSite site = new SPSite(Constants.siteCollectionURL))
{
using (SPWeb web = site.RootWeb)
{
SPList list = web.Lists["Team Discussion"];

//Get the items in the list
SPListItemCollection listItemCollection = list.GetItems(new SPQuery());

//Either you can get the topics this way or the Query method above. Both work fine.
//SPListItemCollection listItemCollection = list.Folders;

//Store all the topics in a list
List topics = new List();

//Iterate through the items
foreach (SPListItem listItem in listItemCollection)
{
//Display the subject and the body of the topic
Console.WriteLine(listItem["Subject"].ToString());
Console.WriteLine(listItem["Body"].ToString());


if (listItem["Parent Folder Id"] != null)
{
Console.WriteLine(listItem["Parent Folder Id"].ToString());
}
else
{
//Store the topic ID for later
topics.Add((Int32)listItem["ID"]);

}


}


//For each topic get all the replies
foreach (int topicID in topics)
{
//Get all the replies
String strQ = @" @TOKEN";
string sTopicID = Convert.ToString(topicID);
strQ = strQ.Replace("@TOKEN", sTopicID);
SPQuery q = new SPQuery();
q.ViewAttributes = "Scope=\"Recursive\"";
q.Query = strQ;

SPListItemCollection replies = list.GetItems(q);

foreach (SPListItem reply in replies)
{
//There's usually o subject, just the body
Console.WriteLine(reply["Body"].ToString());
}
}

}
}

No comments:

Post a Comment