Programmatically Get Version Changes for List Item in SharePoint 2013
-
07-10-2020 - |
Question
Is it possible to get only the changes (changed field values) from every version of a List Item in SP 2013? If so, can anyone please explain it in detail with code?
Solution
There's no direct way provided by the server side API to get version changes. But you can compare the fields of different versions:
using (SPSite site = new SPSite("http://my.domain.com/"))
using (SPWeb web = site.OpenWeb())
{
SPList list = web.GetList("http://my.domain.com/Lists/Stuff");
SPListItem item = list.Items[1];
Console.Out.WriteLine(item.Title);
SPListItemVersion currentVersion = item.Versions[0];
SPListItemVersion previousVersion = item.Versions.Count > 1 ? item.Versions[1] : null;
Console.Out.WriteLine("Version is current: {0}", currentVersion.IsCurrentVersion);
foreach (SPField field in currentVersion.Fields)
{
if (field.ShowInVersionHistory == false)
{
continue;
}
if (previousVersion == null)
{
Console.Out.WriteLine(" > {0} changed to \"{1}\"",
field.StaticName, currentVersion[field.StaticName]);
continue;
}
if (currentVersion[field.StaticName].Equals(previousVersion[field.StaticName]))
{
continue;
}
Console.Out.WriteLine(" > {0} changed from \"{1}\" to \"{2}\"",
field.StaticName, previousVersion[field.StaticName], currentVersion[field.StaticName]);
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange