Skip to main content

How to Copy one datatable to another datatable

Introduction : In this article i am going to share about how to copy a datatable to a new datatable object , and how to add a new row to the datatable.


Overview :
Generally we used datatable object to store out table data, sometime we want to store that datatable temporally to a
another datatable object that time we need to copy the datatable and store to newly created object . It's a best practice
to copy our main datatable when we need that datatable multiple times  and used the copyed object. We can add a new
column dynamically to the newly created object.


Code Example :


Syntex :
DataTable dest = MainDatatable;


Connection String :


<connectionStrings>
   <add name="conn" connectionString="Data Source=anil\SQLEXPRESS2012;Initial Catalog=MyDB;
User ID=sa;Password=sa1" providerName="System.Data.SqlClient" />
 </connectionStrings>


C# Code :


SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ToString()); //Connection String


           con.Open();
           SqlCommand cmd = new SqlCommand("SelectEmployee", con);    // Storeprocedure to get the data
           cmd.CommandType = CommandType.StoredProcedure;
           SqlDataAdapter adp = new SqlDataAdapter(cmd);
           DataTable dt = new DataTable(); // First Inital Datatable object
           adp.Fill(dt); // Data filling on the dt object
           con.Close();

// Here we got our main Datatable 'dt'


           DataTable dt2 = new DataTable(); // Second destination Datatable


           dt2 = dt; // Copying dt data to dt2 // other way ; dt2=dt.copy();
         



//Here we a going to add a new column to the datatable with the specific column possition.
// Here the new column name is Index with integer type.

 int counter = 0;
// Adding columns column name as "Index"
  dt2.Columns.Add("Index", typeof(Int32)).SetOrdinal(0);   // SetOrdinal(0) for placing the column possition
// Adding value 'counter' to  newly created column Index one by one
           foreach (DataRow drow in dt2.Rows)
           {
               drow["Index"] = counter;
               counter++;
           }


Important Note :
In above example i used con for database connection , it is not a mandatory to use con as a connection string you can use
your own keyword.


Here some namespace is required ,
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


Conculation :

This is how we can copy a datatable to a another datatable and a row dynamically.

Comments