Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find latest approved version of an SPListItem

I am trying to iterate through the SPListItem.Versions collection to find the latest approved list item.

My list item has three versions: the first two are approved, the last is in draft. But my code says they're all in draft! Please help!

// Iterate through all versions
for (int index = 0; index < item.Versions.Count; index++)
{
    SPListItem versionedItem = item.Versions[index].ListItem;

    // Check if moderation information is set to approved
    if (versionedItem.ModerationInformation.Status.Equals(SPModerationStatusType.Approved))
    {
        // We found an approved version!
        itemFound = versionedItem;
    }
}
like image 908
Martin Larsson Avatar asked Sep 02 '09 07:09

Martin Larsson


2 Answers

The way Mattias recommends and you have implemented is the best way to do it. It's a little awkward but still efficient as the items are ordered from most recent to oldest. This means you are likely to get a match on the published version quickly.

Expanding on the MSDN SPListItemVersionCollection article (specifically Sebastian Wojciechowski's addition):

// Current version of the item (note: this may be a draft)
SPListItem.Versions[0]

// Previous version of the item
SPListItem.Versions[1]

// First version of the item
SPListItem.Versions[SPListItem.Versions.Count - 1]
like image 142
Alex Angas Avatar answered Oct 28 '22 15:10

Alex Angas


item.Versions[index] returns a SPListItemVersion instance, and SPListItemVersion.ListItem returns the parent SPListItem. So your versionedItem will end up refering to the same object as item, and you're checking the same version over and over again.

I believe you actually want to check

if (item.Versions[index].Level == SPFileLevel.Published) {
  // check item.Versions[index].VersionLabel
}
like image 38
Mattias S Avatar answered Oct 28 '22 16:10

Mattias S