简体   繁体   中英

Copy rows from one Datatable to another DataTable?

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

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.

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

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

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

受以下版本支持:4、3.5 SP1,您现在可以只调用对象上的方法。

DataTable dataTable2 = dataTable1.Copy()

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

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

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);   
 } 
 private void CopyDataTable(DataTable table){
     // Create an object variable for the copy.
     DataTable copyDataTable;
     copyDataTable = table.Copy();
     // Insert code to work with the copy.
 }

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.

To copy whole datatable just do this:

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

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.

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

Not that anyone is still reading this thread by now but...

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);
  }
//use Merge
//this will append all rows of newDataTable with oldDateTale
oldDateTale.Merge(newDataTable);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM