Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » ADO.NET & Database » Copying Data from one DataTable to Another using ImportRow

Copying Data from one DataTable to Another using ImportRow

I recently have been engaged in an assignment where I had to copy large chunks of data from one DataTable to another. This article talks about how DataTable.ImportRow method may be more effective than copying direct rows.

Author Rank :
Page Views : 56658
Downloads : 523
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
DataTableRowTransfer.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

I recently have been engaged in an assignment where I had to copy large chunks of data from one dataset to another in memory. When I say large chunks, I am talking about hundreds of thousands of rows. Not only I had to copy the data but go through each row of the dataset, do some calculations, and update the rows of new dataset.

To do so, I decided to use DataTable objects. If you go through the rows of a DataTable and direct copy rows from one DataTable, you will get an exception saying "Row is already being used by another table".

The simplest way is to clone an existing DataTable, loop through all rows of source DataTable and copy data from column by column and add row to the destination DataTable. The following code does the same:

For Each dr As DataRow In sourceTable.Rows

    r = destinationTable.NewRow

    r("Name") = dr("Name")

    r("City") = dr("City")

    r("Cost") = dr("Cost")

    destinationTable.Rows.Add(r)

Next 

 

DataTable.ImportRow Method

The second method is using DataTable.ImportRow method. The ImportRow method of DataTable copies a row into a DataTable with all of the properties and data of the row. It actually calls NewRow method on destination DataTable with current table schema and sets DataRowState to Added. The following code does the same as we did in the previous code snippet.

For Each dr As DataRow In sourceTable.Rows

    destinationTable.ImportRow(dr)

Next
 

Performance

The following chart compares the time versus number of records copied. If you have small number of rows, it will not make a big difference but when you start importing hundreds of thousands of rows, for example, 500,000 in my case, there was a difference of almost 9 seconds.

 

Here are the numbers for both methods:

When I tried to copy over 1 million rows, DataTable.ImportRow method took 17 seconds but I got memory exception using direct copy method.

Summary

When it comes to copying bulk of data in memory from one DataTable to another, DataTable.ImportRow method comes handy. This article compares both direct copy and ImportRow method and we saw ImportRow method may reduce the processing time when dealing with large data. See the attached source code for more details.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM). 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
ImportRow dosn't work! by Mordechai On November 23, 2008
Dear Mahesh I wanted to copy a single row at a specified position to aanother dt. There are two items: 0 is ID 1 is Description If I use the ImportRow method it creates a new row in the dt but only copies in teh value for item 1 (the description). Item 0 (the ID) is blank!!!! ds.Tables("Prv").ImportRow(ds.Tables("ChooseMenus").Rows(intRow)) When I use the NewRow method and copy over the two items manually then it works fine. rwTemp = ds.Tables("Prv").NewRow rwTemp.Item(0) = ds.Tables("ChooseMenus").Rows(intRow).Item(0) rwTemp.Item(1) = ds.Tables("ChooseMenus").Rows(intRow).Item(1) ds.Tables("Prv").Rows.Add(rwTemp) Why doesn't the ImportRow copy both item values??? Mordechai
Reply | Email | Modify 
Re: ImportRow dosn't work! by Rodney On February 28, 2010
Try a clone first:

dtNew = dtOld.Clone

Reply | Email | Modify 
Clear Explanation by Menaka On September 17, 2010
Thank you Mahesh Chand,

You have given clear explanation and have covered overall requirement regarding this stuff.
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.