193

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

15 Answers 15

291
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.

16
  • 27
    Wouldn't this result in "This row already belongs to another table."
    – McArthey
    Jun 6, 2012 at 19:59
  • 15
    @McArthey No, it wouldn't; a new row is being created from the values in the existing row. The row itself is not being added to the other DataTable. Jun 7, 2012 at 0:31
  • 21
    @DawoodAbbasi That would only happen if you left out the ItemArray part at the end of the expression. Make sure you are adding the row's values, not the row itself. Jul 11, 2013 at 6:50
  • 5
    @DawoodAbbasi Refer to the MSDN documentation for the DataTable.Clone method: msdn.microsoft.com/en-us/library/… Jul 11, 2013 at 7:26
  • 11
    Though your answer technically is correct, your code sample doesn't address your assumptions. The answer by @RageeshGr handles all the assumptions and IMHO is written more concisely and is less error prone. Oct 24, 2013 at 12:13
124

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);
   }
}
4
  • If I am no longer need to use dttableOld after import, do I still need to use Clone()?
    – Sam
    Feb 27, 2019 at 12:40
  • 2
    @Sam regarding your question, Clone is to copy the table structure, if your table is already the same data-type, then you don't need it. Jun 25, 2020 at 18:29
  • There is better way to do this. entityColumnMetadata = changedColumnMetadata.AsEnumerable().Where(dataRow => entityName.Equals(dataRow["EntityName"])).CopyToDataTable();
    – yuvraj
    Nov 6, 2020 at 8:03
  • +1 Good answer. Worth pointing out that DataTable::ImportRow is more tolerant, compared with DataTable::Rows::Add(...), when it comes to the number and order of columns . If a column is missing in the imported row, the value is set to NULL.
    – AlainD
    Apr 6, 2022 at 22:32
23

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);
    }
1
  • @ManojSavalia, so what is the alternative that doesn't cost performance?
    – Sam
    Feb 27, 2019 at 12:42
22

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);
1
  • This is a much better approach because it uses built-in capability to range-copy or even select rows from one DataTable to another without explicitly iterating through each, unlike all of the foreach loop, .ForEach method based answers.
    – David Burg
    Aug 30, 2018 at 22:36
16

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

DataTable dataTable2 = dataTable1.Copy()
1
  • 3
    Technically this creates a copy of a datatable. While it's not explicitly stated in the question, it's possible that dataTable2 already exists and has other rows in it which we don't want to lose. Also, the question specifically states "specific rows", whereas this only handles all rows.
    – Matt
    Mar 8, 2016 at 22:24
7

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));
3
  • Which is basically a foreach. Also, you're not filtering through a condition, as requested by the OP.
    – Eric Wu
    Jul 20, 2016 at 19:51
  • Now if I clear out the sourceTable will the destTable also clear?
    – Si8
    Feb 20, 2017 at 15:00
  • I want to be able to assign a value and clear out the original variable without clearing out the destination.
    – Si8
    Feb 20, 2017 at 15:05
6

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);   
 } 
1
  • An even easier way to do this is instead of using a for, use a foreach (Datarow dr...)
    – Freerey
    Jan 15, 2021 at 20:03
3

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);
}
0
2

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

1
 private void CopyDataTable(DataTable table){
     // Create an object variable for the copy.
     DataTable copyDataTable;
     copyDataTable = table.Copy();
     // Insert code to work with the copy.
 }
1
  • your code works perfect to me, is a very simple code ,thanks
    – Esraa_92
    Jun 28, 2017 at 13:17
0

To copy whole datatable just do this:

DataGridView sourceGrid = this.dataGridView1;
DataGridView targetGrid = this.dataGridView2;
targetGrid.DataSource = sourceGrid.DataSource;
1
  • 2
    the question is on how to copy specific rows from a data table, not the whole thing.
    – jtate
    Jan 2, 2019 at 20:13
0

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.

0

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.

0

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);
0

use Merge, this will append all rows of newDataTable with oldDateTale

oldDateTale.Merge(newDataTable);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.