I am trying to execute following code. All I am trying to do is to copy one column from a dataset into one of the columns of another dataset. The code is as follows:
int i=0
foreach (DataRow dr in ds_input.Tables[0].Rows)
{
ds_output.Tables["output"].Rows[i]["Serial_Number"] = dr["Serial Number"].ToString();
i++;
}
While assigning column value of dr
to ds
, the compiler returns the following error:
There is no row at position 0.
Despite making the following addition, it returns the same error:
int i=0;
foreach (DataRow dr in ds_input.Tables[0].Rows)
{
ds_output.Tables["output"].NewRow();
ds_output.Tables["output"].Rows[i]["Serial_Number"] = dr["Serial Number"].ToString();
i++;}
You have to add the
DataRow
to theDataTable
. If the output- and the input-tables have the same columns you could useDataTable.Clone
to clone the table which does not copy the data. Then you can either useDataTable.ImportRow
to create a copy of theDataRow
from the input table and add that to the output-table. Or you could usetable.Rows.Add
to add a newDataRow
and use theItemArray
(all fields) of the input-DataRow:If you want to create a complete copy of the input-table you can use
DataTable.Copy
: