Copy rows from one Datatable to another DataTable?

C#Datatable

C# Problem Overview


How can I copy specific rows from DataTable to another Datable in c#? There will be more than one row.

C# Solutions


Solution 1 - C#

foreach (DataRow dr in dataTable1.Rows) {
    if (/* some condition */)
        dataTable2.Rows.Add(dr.ItemArray);
}

The above example assumes that dataTable1 and dataTable2 have the same number, type and order of columns.

Solution 2 - C#

Copy Specified Rows from Table to another

// here dttablenew is a new Table  and dttableOld is table Which having the data 

dttableNew  = dttableOld.Clone();  

foreach (DataRow drtableOld in dttableOld.Rows)
{
   if (/*put some Condition */)
   {
      dtTableNew.ImportRow(drtableOld);
   }
}

Solution 3 - C#

Try This

    String matchString="ID0001"//assuming we have to find rows having key=ID0001
    DataTable dtTarget = new DataTable();
    dtTarget = dtSource.Clone();
    DataRow[] rowsToCopy;
    rowsToCopy = dtSource.Select("key='" + matchString + "'");
    foreach (DataRow temp in rowsToCopy)
    {
        dtTarget.ImportRow(temp);
    }

Solution 4 - C#

Check this out, you may like it (previously, please, clone table1 to table2):

table1.AsEnumerable().Take(recodCount).CopyToDataTable(table2,LoadOption.OverwriteChanges);

Or:

table1.AsEnumerable().Where ( yourcondition  ) .CopyToDataTable(table2,LoadOption.OverwriteChanges);

Solution 5 - C#

Supported in: 4, 3.5 SP1, you can now just call a method on the object.

DataTable dataTable2 = dataTable1.Copy()

Solution 6 - C#

As a result of the other posts, this is the shortest I could get:

DataTable destTable = sourceTable.Clone();
sourceTable.AsEnumerable().Where(row => /* condition */ ).ToList().ForEach(row => destTable.ImportRow(row));

Solution 7 - C#

I've created an easy way to do this issue

 DataTable newTable = oldtable.Clone();    
 for (int i = 0; i < oldtable.Rows.Count; i++)
 {
   DataRow drNew = newTable.NewRow();    
   drNew.ItemArray = oldtable.Rows[i].ItemArray;    
   newTable.Rows.Add(drNew);   
 } 

Solution 8 - C#

below sample would be the fastest way to copy one row. each cell is being copied based on the column name. in case you dont need a specific cell to copy then have a try catch or add if. if your going to copy more than 1 row then loop the code below.

DataRow dr = dataset1.Tables[0].NewRow();
for (int i = 0; i < dataset1.Tables[1].Columns.Count; i++)
{
    dr[dataset1.Tables[1].Columns[i].ColumnName] = dataset1.Tables[1].Rows[0][i];
}

datasetReport.Tables[0].Rows.Add(dr);

dataset1.Tables[1].Rows[0][i]; change the index 0 to your specified row index or you can use a variable if your going to loop or if its going to be logical

Solution 9 - C#

 private void CopyDataTable(DataTable table){
     // Create an object variable for the copy.
     DataTable copyDataTable;
     copyDataTable = table.Copy();
     // Insert code to work with the copy.
 }

Solution 10 - C#

I needed to copy rows from multiple tables with the same structure into a new table to be used as a datasource for datagridview:

// Generate DataTable[] alltables from multiple datatables

DataTable newTable = alltables[0].Clone();
foreach (DataTable dt in alltables)
{
   for (int i = 0; i < dt.Rows.Count; i++)
      newTable.Rows.Add(dt.Rows[i].ItemArray);
}

Solution 11 - C#

To copy whole datatable just do this:

DataGridView sourceGrid = this.dataGridView1;
DataGridView targetGrid = this.dataGridView2;
targetGrid.DataSource = sourceGrid.DataSource;

Solution 12 - C#

For those who want single command SQL query for that:

INSERT INTO TABLE002 
(COL001_MEM_ID, COL002_MEM_NAME, COL002_MEM_ADD, COL002_CREATE_USER_C, COL002_CREATE_S)
SELECT COL001_MEM_ID, COL001_MEM_NAME, COL001_MEM_ADD, COL001_CREATE_USER_C, COL001_CREATE_S
FROM TABLE001;

This query will copy data from TABLE001 to TABLE002 and we assume that both columns had different column names.

Column names are mapped one-to-one like:

COL001_MEM_ID -> COL001_MEM_ID

COL001_MEM_NAME -> COL002_MEM_NAME

COL001_MEM_ADD -> COL002_MEM_ADD

COL001_CREATE_USER_C -> COL002_CREATE_USER_C

COL002_CREATE_S -> COL002_CREATE_S

You can also specify where clause, if you need some condition.

Solution 13 - C#

There is better way to do this.

DataTable targetDataTable = new DataTable(); targetDataTable = changedColumnMetadata.AsEnumerable().Where(dataRow => entityName.Equals(dataRow["EntityName"])).CopyToDataTable();

Please try this and let me know in case of any issues.

Solution 14 - C#

You can do it calling the DataTable.Copy() method, for example:

   DataSet ds = new DataSet();
   System.Data.DataTable dt = new System.Data.DataTable();
   dt = _BOSearchView.DS.Tables[BusLib.TPV.TableName.SearchView].Copy();
   ds.Tables.Add(dt);
   UltGrdSaleExcel.SetDataBinding(ds, dt.TableName, true);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkartalView Question on Stackoverflow
Solution 1 - C#Bradley SmithView Answer on Stackoverflow
Solution 2 - C#Rageesh Geetha RamanView Answer on Stackoverflow
Solution 3 - C#ZiaView Answer on Stackoverflow
Solution 4 - C#EstevezView Answer on Stackoverflow
Solution 5 - C#AmirView Answer on Stackoverflow
Solution 6 - C#MeielView Answer on Stackoverflow
Solution 7 - C#Willie ChengView Answer on Stackoverflow
Solution 8 - C#Chad DumagasView Answer on Stackoverflow
Solution 9 - C#user1599615View Answer on Stackoverflow
Solution 10 - C#Peter-IrkshnoiView Answer on Stackoverflow
Solution 11 - C#inspironView Answer on Stackoverflow
Solution 12 - C#ManishaView Answer on Stackoverflow
Solution 13 - C#yuvrajView Answer on Stackoverflow
Solution 14 - C#kaushiksutariyaView Answer on Stackoverflow