Pages

Showing posts with label How to Copy ListItem from One List to Another List. Show all posts
Showing posts with label How to Copy ListItem from One List to Another List. Show all posts

Tuesday, March 6, 2012

How to Copy ListItem from One List to Another List

Hello

Here is code how to copy ListItem from one list to another list from eventhandler.
Make sure both list has same List Field Structure.

Here is Code

public override void ItemAdded(SPItemEventProperties properties)
       {

           if (properties.List.Title.Equals("ListA"))
           {
               SPListItem CopyItem = properties.Web.Lists["ListB"].Items.Add();

               foreach (SPField f in properties.ListItem.Fields)
               {
                   //Copy all except attachments.
                   if (!f.ReadOnlyField && f.InternalName != "Attachments"
                       && null != properties.ListItem[f.InternalName])
                   {
                       CopyItem[f.InternalName] = properties.ListItem[f.InternalName];
                   }
               }


               foreach (string fileName in properties.ListItem.Attachments)
               {
                   SPFile file = properties.ListItem.ParentList.ParentWeb.GetFile(properties.ListItem.Attachments.UrlPrefix + fileName);
                   byte[] imageData = file.OpenBinary();
                   CopyItem.Attachments.Add(fileName, imageData);
               }
               CopyItem.Update();

           }
       }

Hope it helps!!!

Disha Shah