Friday, 11 January 2013

Move List Items from one List to Other in SharePoint 2010



We cannot move the list items from one list to other directly. Hence to do achieve this we need to first copy the list item to the destination list & then delete the same from the source list. The following code shows how to move list items from one list to other.

/// MoveToList is a method to move Item from Source List to Destination List
/// <param name="siteUrl">Pass Site url of SiteCollection</param>
/// <param name="Source">Pass Source List Name</param>
/// <param name="Destination">Pass Destination List Name</param>

public void MoveToList(string siteUrl, string Source, string Destination)
{

  SPQuery qry = new SPQuery();    //To query the item
  string camlquery = string.Empty;
  SPListItemCollection Srccollitem;
  SPList destlib;
  SPListItem item;
  SPListItem targetItem;
  try
  {
    using (SPSite rootSite = new SPSite(siteUrl))    //siteUrl is the URL of the site
    {
      using (SPWeb spWeb = rootSite.OpenWeb())
      {
        //The below query gets all the items whose Expiry Date column contains Date Today’s Date or previous date

        camlquery = "<Where>"
                                + "<Lt>"
                                + "<FieldRef Name='Expiry_x0020_Date' />"
                                + "<Value IncludeTimeValue='FALSE' Type='DateTime' ><Today /></Value>"
                                + "</Lt>"
                                + "</Where>";

        qry.Query = camlquery;

        ///Get the Collection of SourceListItem by Caml Query
        Srccollitem = spWeb.Lists[Source].GetItems(qry);

        ///Get the Destination List
        destlib = spWeb.Lists[Destination];

        ///Start of For Loop to move items one by one from Source List to Destination List
        for (int i = Srccollitem.Count - 1; i >= 0; i--)
        {
          item = Srccollitem[i];

        ///First add item to the destination list
          targetItem = destlib.Items.Add();
          ///Start of ForEach Loop to add value of each Field from Source to Destionation
          foreach (SPField f in item.Fields)
          {
             //Copy all except attachments.
             if (!f.ReadOnlyField && f.InternalName != "Attachments"
&& null != item[f.InternalName])
             {
                 targetItem[f.InternalName] = item[f.InternalName];
             }
          }
          ///End of ForEach Loop
          spWeb.AllowUnsafeUpdates = true;

        ///Update The Destination List
          targetItem.Update();

        ///Now once the Destination list is updated, Delete the item from the source list
          item.Delete();
          spWeb.AllowUnsafeUpdates = false;
        }
        ///End of For Loop.
      }
    }
  }
  catch (Exception ex)
  {

  }
}

No comments:

Post a Comment