How can we copy the data of the datacolumn of the datatable to another datatable?

こ雲淡風輕ζ 提交于 2019-12-21 23:13:13

问题


How can we copy one datacolumn with data from one datatable to another datatable ? I have datatable like

DataTable datatable1=new DataTable();

and there are four columns in that table but I want only one column.So I am doing like

DataTable datatable2=new DataTable(); 
addressAndPhones2.Columns.Add(addressAndPhones.Columns[0].ColumnName,addressAndPhones.Columns[0].DataType);

but this just adds the column but I want to copy the data for that column to the datatable2.That is I want to copy the datacolumn with data from one datatable to another datatable.


回答1:


Two solutions spring to mind:

  1. after creating the column, loop through all rows to copy the data from the source to the target.
  2. Do a datatable1.Copy() to copy all columns+data and delete the ones you don't need.

The second one is simpler to code but will copy unneeded data (which means extra time and memory).

For the first one, IF you have prepared the destiny-datatable AND the columnnames (and types) in source and destiny are the same:

private void CopyColumns(DataTable source, DataTable dest, params string[] columns)
{
  foreach (DataRow sourcerow in source.Rows)
  {
     DataRow destRow = dest.NewRow();
     foreach(string colname in columns)
     {
        destRow[colname] = sourcerow[colname];
     }
     dest.Rows.Add(destRow);
  }
}

You can use this like:

CopyColumns(source, destiny, "Column1", "column2");

naming any number of columns.




回答2:


You can loop over all rows with something like this:

private void CopyColumn(DataTable srcTable, DataTable dstTable, string srcColName, string dstColName)
{
    foreach (DataRow row in srcTable.Rows )
    {
        DataRow newRow = dstTable.NewRow();
        newRow[dstColName] = row[srcColName];
        dstTable.Rows.Add(newRow);
    }
}


来源:https://stackoverflow.com/questions/2583898/how-can-we-copy-the-data-of-the-datacolumn-of-the-datatable-to-another-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!