سؤال

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 the DataTable. If the output- and the input-tables have the same columns you could use DataTable.Clone to clone the table which does not copy the data. Then you can either use DataTable.ImportRow to create a copy of the DataRow from the input table and add that to the output-table. Or you could use table.Rows.Add to add a new DataRow and use the ItemArray(all fields) of the input-DataRow:

DataSet ds_output = new DataSet();
DataTable tblOutput = ds_input.Tables[0].Clone();
ds_output.Tables.Add(tblOutput);
foreach (DataRow dr in ds_input.Tables[0].Rows)
{
    tblOutput.ImportRow(dr);
    // or:
    DataRow newRow = tblOutput.Rows.Add();
    newRow.ItemArray = dr.ItemArray;
}

If you want to create a complete copy of the input-table you can use DataTable.Copy:

DataTable tblOutput = ds_input.Tables[0].Copy(); // nothing more needed
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top