Microsoft Knowledge Base Email Alertz

KBAlertz.com: (308909) - This article demonstrates how to copy specific DataRow objects from one table to another by using the ImportRow method of the DataTable class. back to the top How to Copy DataRows Between DataTables Before you use the ImportRow method, you must ensure...

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com

ASP.NET 3.5 Web Hosting with Windows 2008 and SQL 2008: Click Here!
Discount ASP.NET Hosting
ASP.NET 2.0 and 3.5
Windows2008 and SQL2008
US and UK Hosting
The ad says 3 - but KBAlertz referrals get
** SIX MONTHS FREE **




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




Article ID: 308909 - Last Review: May 13, 2007 - Revision: 2.5

How To Copy DataRows Between DataTables by Using Visual C# .NET

This article was previously published under Q308909

On This Page

SUMMARY

This article demonstrates how to copy specific DataRow objects from one table to another by using the ImportRow method of the DataTable class.


How to Copy DataRows Between DataTables

Before you use the ImportRow method, you must ensure that the target table has the identical structure as the source table. This sample uses the Clone method of DataTable class to copy the structure of the DataTable, including all DataTable schemas, relations, and constraints.

This sample uses the Products table that is included with the Microsoft SQL Server Northwind database. The first five rows are copied from the Products table to another table that is created in memory.
  1. Create a new Visual C# Console Application project. Class1.cs is created by default.
  2. If the Code window is not open, right-click Class1.cs in Solution Explorer, and click View Code.
  3. Delete all of the code from the Code window.
  4. Copy the following code, and paste it in the Code window:
    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace ImportRowCS
    {
        class Class1
        {
            static void Main(string[] args)
            {
                // 
                // TODO: Add code to start application here.
                DataTable tblProducts = new  DataTable();
                DataTable tblProductsCopy = new DataTable();
    
                int tblProductsCount;
                int tblProductsCopyCount;
                int i;
        // Change the connection string to your server.
        SqlConnection Conn = new SqlConnection("Server=(local);
                                                database=Northwind;
                                                UID=<User ID>;PWD=<Password>");
        // Create the DataAdapter.
        SqlDataAdapter da = new SqlDataAdapter("Select * from products", Conn);
        // Fill the DataSet with data.
        DataSet ds = new DataSet();
        da.Fill(ds, "products");
        tblProducts = ds.Tables["products"];
        tblProductsCount = tblProducts.Rows.Count;
    
        // Write the number of rows in the Products table to the screen.
        Console.WriteLine("Table tblProducts has " + tblProductsCount.ToString() + " Rows");
    
        // Loop through the top five rows, and write the first column to the screen.
        for (i=0; i<=4;++i)
                {
                    Console.WriteLine("Row(" + i.ToString() + ") = " + tblProducts.Rows[i][1]);
                }
           
    
        // Use Clone method to copy the table structure (Schema).
        tblProductsCopy = tblProducts.Clone();
    
        // Use the ImportRow method to copy from Products table to its clone.
                for (i=0; i<=4;++i)
                {
                tblProductsCopy.ImportRow(tblProducts.Rows[i]);
                }
            tblProductsCopyCount = tblProductsCopy.Rows.Count;
        // Write blank line.
        Console.WriteLine();
        // Write the number of rows in tblProductsCopy table to the screen.
        Console.WriteLine("Table tblProductsCopy has " + 
                          tblProductsCopyCount.ToString() + " Rows");
    
        // Loop through the top five rows, and write the first column to the screen.
                for(i = 0; i<=tblProductsCopyCount - 1;++i)
                {
                    Console.WriteLine("Row(" + i.ToString() + ") = " + tblProductsCopy.Rows[i][1]);
                }
    
        // This line keeps the console open until you press ENTER.
        Console.ReadLine();
    
            }
        }
    }
    					
  5. Modify the connection string as appropriate for your environment.
  6. Press the F5 key to build and run the project. Note that the program's output appears as follows in the Command window:
    Table tblProducts has 77 Rows
    Row(0) = Chai
    Row(1) = Chang
    Row(2) = Aniseed Syrup
    Row(3) = Chef Anton's Cajun Seasoning
    Row(4) = Chef Anton's Gumbo Mix
    
    Table tblProductsCopy has 5 Rows
    Row(0) = Chai
    Row(1) = Chang
    Row(2) = Aniseed Syrup
    Row(3) = Chef Anton's Cajun Seasoning
    Row(4) = Chef Anton's Gumbo Mix
    						
  7. When you are finished, press ENTER to close the Command window.

Additional Notes

You can use the Copy method of a DataTable object to copy the entire DataTable:
DataTable DataTable1 = new DataTable();
DataTable DataTable2 = new DataTable();
DataView DataView1 = new DataView();
DataSet DataSet1 = new DataSet();

// Copy the entire DataTable.
DataTable2 = DataTable1.Copy();
DataSet1.Tables.Add(DataTable2);
				
You can also copy DataRow objects from the results of a filtered DataView class or from the results of a Select method. For example:
// Copy from the results of a Select method.
foreach (DataRow MyDataRow in DataTable1.Select("Region = 'WA'"))
{
	DataTable2.ImportRow(MyDataRow);
}
Console.WriteLine(DataTable2.Rows.Count);
Console.ReadLine();

// Copy from the results of a DataView.
DataView1 = DataTable1.DefaultView;
DataView1.RowFilter = "Region = 'WA'";
for (int i = 0; i <= DataView1.Count - 1; ++i)
{
	DataTable2.ImportRow(DataView1[I].Row);
}
Console.WriteLine(DataTable2.Rows.Count);
Console.ReadLine();
				

REFERENCES

For more information on ADO.NET objects and syntax, refer to the following topic in the Microsoft .NET Framework Software Development Kit (SDK) documentation:
Accessing Data with ADO.NET
http://msdn2.microsoft.com/en-us/library/e80y5yhx(vs.71).aspx (http://msdn2.microsoft.com/en-us/library/e80y5yhx(vs.71).aspx)

APPLIES TO
  • Microsoft ADO.NET 1.1
  • Microsoft ADO.NET 1.0
  • Microsoft Visual C# .NET 2003 Standard Edition
  • Microsoft Visual C# .NET 2002 Standard Edition
Keywords: 
kbdatabase kbhowtomaster kbsqlclient kbsystemdata KB308909
       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Renso Report As Irrelevant  
Written: 1/25/2005 7:56 AM
Very helpfull article, have looked high and low on how to copy data from one table to another without "inheriting" the source tables structure. Thanks.

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please