How to copy a DataTable to a SharePoint SPList?

Azra picture Azra · Jul 14, 2009 · Viewed 7.5k times · Source

I have my source list data in the sourceList data table and want to copy that data to its root list.

How can I do that?

private void MoveToTopTaskList(DataTable sourceList, SPSite DestinationSiteCollection)
{
    SPWeb Destinationsite = DestinationSiteCollection.OpenWeb();
    SPList DestinationList = Destinationsite.Lists[TASKS];
    SPListItem DestinationListItem = DestinationList.Items.Add();

    foreach (DataRow row in sourceList.Rows)
    {

    }
}

Answer

Kusek picture Kusek · Jul 14, 2009

Best Approach for the above case is to Use the ProcessBatchData Method of the SPWeb Object. This will help you to update List items in to the List in Batch.

  1. You need to build an XML tags that will have details for inserting the data to the list.
  2. If you have large number of records to be inserted to the list consider spliting it in to smaller batchs. Say if you have 1000 records do it in two 500 sets.
  3. While building the XML make sure you use StringBuilder class to append the string.
  4. Refer these Links Link1 Link2 Link3 for more information on ProcessBatchData

In case if you want to do it using the OM. Then follow code

`SPWeb Destinationsite = DestinationSiteCollection.OpenWeb();
SPList DestinationList = Destinationsite.Lists[TASKS];    
SPListItem DestinationListItem = DestinationList.Items.Add();
  foreach (DataRow row in sourceList.Rows)
{
    DestinationListItem = DestinationList.Items.Add();
    DestinationListItem["Field1"]=row["Col"].ToString();
    DestinationListItem["Fieldn"]=row["Coln"].ToString();
    DestinationListItem.Update()

}

`