Question

I have SharePoint 2007 discussion list. I want to iterate over all items in the list, so I do the following:

var list = web.Lists["discussion"];
var listItems = list.Items;
foreach (var listItem in ListItems)
{
    // do something
}

However the iteration doesn't seem to work. The Items collection is always empty. Interesting to notice

list.ItemCount

will return "4", whereas

list.Items.Count

will return "0".

Has anyone encounterd such a problem before? I tried another list (custom list), and there I can iterate just fine. Seems to be specific to the discussion-list.

Was it helpful?

Solution

Looks like the trick is to use list.Folders:

foreach (SPListItem folder in myDiscussionList.Folders)
{
    // do something
}

Source: How to Read All Discussions and Replies

OTHER TIPS

Here is my answer to somewhat similar question. It is 2010 solution in Powershell but you can easily convert it Moving a Discussion from a Discussion Board to another?

Addition:

I posted my original answer from my mobile device so I feel obligated to provide more info.

To simplify things: In discussion list discussions are folders and messages are items inside folders. Since there are no items on 'root' list.Items.Count will return 0 and list.ItemCount will return number of folders/discussions.

And now the fun stuff.

Get all discussions (@KitMenke already provided this)

foreach (SPListItem discussion in list.Folders)
{

}

Get all discussions with all messages

foreach (SPListItem discussion in list.Folders)
{
    //discussion.Title is discussion title
    SPQuery query = new SPQuery();
    query.Folder = discussion.Folder;
    SPListItemCollection messages = list.GetItems(query);
    foreach(SPListItem message in messages)
    {
        // message["TrimmedBody"] is message body
    }
}

Get all messages

SPQuery query = new SPQuery();
query.ViewAttributes = "Scope='Recursive'";
SPListItemCollection messages = list.GetItems(query);
foreach (SPListItem message3 in messages3)
{
    // message.DisplayName is discussion title !
    // message["TrimmedBody"] is message body
}

Get all messages from current user

SPQuery query = new SPQuery();
query.Query = "<Eq><FieldRef Name='Author'/><Value Type='Integer'><UserID/></Value></Eq>";
query.ViewAttributes = "Scope='Recursive'";
SPListItemCollection messages = list.GetItems(query);
foreach (SPListItem message in messages)
{
    // message.DisplayName is discussion title !
    // message["TrimmedBody"] is message body
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top