forge

Creating a new set of list items from one list into another

Here’s the other bit of code having to do with the pesky created/modified dates.  This is just a function and not a whole program.  It deletes all of the items in a destination list and then copies all of the items from the source list.  The interesting bit is that the created/modified fields hold up to this mechanism.  You can create a new list item that maintains the created/modified dates of the original item.  As with the previous code — this is not intended for direct use.  It’s designed to show you how you might copy the created/modified fields from one list to another.

/// <summary>
/// Copy list data from one list to another
/// </summary>
/// <param name=”spListRef”>The source of the list data</param>
/// <param name=”spListTarget”>The target (destination) of the list data</param>
public static void CopyListData(SPList spListRef, SPList spListTarget)
{
if (spListRef.BaseType == SPBaseType.DocumentLibrary)
{
CopyDocumentData(spListRef, spListTarget);
return;
}
SPListItem spListItemTarget;

// Delete all Items
while (spListTarget.Items.Count > 0)
{
spListTarget.Items.Delete(0);
}

foreach(SPListItem spListItemRef in spListRef.Items)
{
spListItemTarget = spListTarget.Items.Add();
foreach(SPField spFieldRef in spListItemRef.Fields)
{
if (spFieldRef.Type != SPFieldType.Attachments &&
spFieldRef.Type != SPFieldType.Calculated &&
spFieldRef.Type != SPFieldType.Computed &&
spFieldRef.Type != SPFieldType.Counter &&
spFieldRef.Type != SPFieldType.CrossProjectLink &&
spFieldRef.Type != SPFieldType.Error &&
spFieldRef.Type != SPFieldType.File &&
spFieldRef.Type != SPFieldType.Invalid &&
spFieldRef.InternalName != “owshiddenversion” &&
spFieldRef.InternalName != “InstanceID” &&
spFieldRef.InternalName != “Order” &&
spFieldRef.InternalName != “GUID”
)
{
spListItemTarget[spFieldRef.InternalName] = spListItemRef[spFieldRef.InternalName];
}
}

foreach(string attachmentUrl in spListItemRef.Attachments)
{
string fullUrl = string.Format(“Lists/{0}/Attachments/{1}/{2}”, spListRef.Title, spListItemRef.ID,
attachmentUrl);
SPFile srcAttach = spListRef.ParentWeb.GetFile(fullUrl);
spListItemTarget.Attachments.Add(attachmentUrl, srcAttach.OpenBinary());
}
spListItemTarget.Update();
}
}

4 replies

Comments are closed.