0

My DataTable has many columns more than 35 columns. Among them I want to copy the first column "SYMBOL_QA" data to another new DataTable.

I searched in internet but did not found any suitable approaches. One approach I found was to copy the whole DataTable as it is, then delete the unwanted columns. But I have 35 columns and deleting all of them one by one will not be good approach.

protected void SendDataTable(DataTable dSource)
{
    DataTable dTarget = new DataTable();
    dTarget.Columns.Add(new DataColumn("SYMBOL_QA_"));
    int rowIdx = 0;
    dTarget.AsEnumerable().All(row => { row["SYMBOL_QA_"] = dSource.Rows[rowIdx++]["SYMBOL_QA"]; return true; });

}

This code block is not working. How can I do this ?

user4221591
  • 2,084
  • 7
  • 34
  • 68
  • If you only want one column why not convert to a list of the data type? What is the purpose of creating another datatable? – Ryan Wilson Mar 18 '19 at 17:55
  • Possible duplicate of [Copy specific columns from one DataTable to another](https://stackoverflow.com/questions/18402324/copy-specific-columns-from-one-datatable-to-another) – JSteward Mar 18 '19 at 17:56

2 Answers2

3

I think that the easiest method to do what you have requested is through the DataView.ToTable method

DataTable dTarget = dSource.DefaultView.ToTable(false, "SYMBOL_QA");

It is just a single line and it

Creates and returns a new DataTable based on rows in an existing DataView.

Steve
  • 213,761
  • 22
  • 232
  • 286
1
protected DataTable CopyColumn(DataTable sourceTable, string columnName)
{
    DataTable result = new DataTable();
    result.Columns.Add(new DataColumn(columnName));

    foreach(DataRow sourceRow in sourceTable.Rows)
    {
         var destRow = result.NewRow();
         destRow[columnName] = sourceRow[columnName];
         result.Rows.Add(destRow);
    }
    return result;
}
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794