Tuesday, March 16, 2010

How to reply on discussion thread programmatically – Part 2

Hi All,

I am back with more details on discussion thread reply programmatically. In part 1, we simply went through how we can create discussion list and create simple reply.

This post will tell you more details regarding it.

Let us start with replying individual thread reply. First you need to loop through the subjects or best it to query discussion list with the help of SPQuery on subject field, so that you get the SPListItem object in your hand to play with.

using (SPSite objSite = new SPSite("{site URL}"))
{
SPWeb objWeb = objSite.OpenWeb("Web Name");

objWeb.AllowUnsafeUpdates = true;

SPList objList = objWeb.Lists["{discussion list name}"];

//remember objList.Folders will return you all discussion subjects. objList .ItemCount will return you all discussion along with their replies, objList .Items.count will return only replies. So now we will loop through all subjects,for demo I have also three discussion threads in my list. In real scenario, query the list and get SPListItem object.
foreach (SPListItem lstsubject in objList.Folders )
{

strSubject = lstsubject.Name;

if(strSubject.Contains(“test subject to reply”))
{
SPListItem parentitem = objList.GetItemById(lstsubject.ID); //Get //the SPListItem for that discussion subject thread.

//Create reply to that subject.

SPListItem reply = SPUtility.CreateNewDiscussionReply(parentitem);

reply["Body"] = "Yippi…This is my reply programmatically";
reply.Update();
}
}
objWeb.AllowUnsafeUpdates = false;
}


Hope this will help you a bit.