Monday, February 6, 2012

Copy data between SPListItems for matching fields in SharePoint.

1. Below code snippet will copy all the matching field data from spListItem2 to spListItem1 without hardcoding the field names.

SPListItem spListItem1 = spListItemCollection1[0];
SPListItem spListItem2 = spListItemCollection2[0];
SPFieldCollection spCollContentTypeFields = spListItem1.ContentType.Fields;
foreach (SPField field in spCollContentTypeFields)
{
if (spListItem2.Fields.Contains(field.Id))
{
if (string.Compare(Convert.ToString(spListItem1[field.StaticName]).Trim(), Convert.ToString(spListItem2[field.StaticName]).Trim(), true) != 0)
{
spListItem1[field.Id] = spListItem2[field.Id];
}
}
}
spListItem1.Web.AllowUnsafeUpdates = true;
spListItem1.Update();

Hope this helps, happy coding...

No comments:

Post a Comment