I searched a lot for Server Object code in reading Discussion Board items and replies. Since I was unable to find one, I created the following.
Challenge
You need to programmatically get all discussion items along with their replies.
Procedure
1. This is our Discussion Board.
This is the code to retrieve all discussion items.
- using (SPSite site = new SPSite("http://hpvm"))
- {
- using (SPWeb web = site.OpenWeb())
- {
- SPList list = web.Lists.TryGetList("Discussion Board");
- if (list != null)
- {
- SPQuery query = new SPQuery();
- query.ViewFields = "<FieldRef Name='Title' />";
-
- SPListItemCollection itemColl = list.GetItems(query);
- foreach (SPListItem item in itemColl)
- {
- System.Console.WriteLine(item["Title"].ToString());
- }
- }
- }
- }
2. Make sure the code is returning values like this.
Now we are writing the code to return the replies.
- private static void GetReplies(SPList list, SPListItem item)
- {
- SPQuery query = new SPQuery();
- query.Folder = item.Folder;
-
- SPListItemCollection collection = list.GetItems(query);
-
- SPListItem replyItem = collection[0];
- string body = (string)replyItem["Body"];
- string author = (string)replyItem["Author"];
-
- System.Console.WriteLine(body);
- System.Console.WriteLine(author);
- }
The following is the output on running the console application.
3. You can see the Author is returned mixing with ID. You can use the following method to extract the correct User Name from the string.
- private static string GetUserName(string author, SPList list)
- {
- string result = author;
-
- if (author.Contains(";"))
- {
- int id = int.Parse(author.Split(';')[0]);
- SPUser user = list.ParentWeb.SiteUsers.GetByID(id);
- result = user.Name;
- }
-
- return result;
- }
4. Now the user name seems to be better.
I am creating a Console Application to retrieve the same.
References
γγγγ
http://bit.ly/1tIX5NVSummary
In this article we have explored how to fetch Discussion Board Items and Replies. The source code is attached here with the article.