5

I have two datatables, I am trying to copy row from one table to another, I have tried this. the thing is that my tables are not exactly the same, both tables have common headers, but to the second table have more columns, therefore I need "smart" copy, i.e to copy the row according to the column header name.

d1:

+--------+--------+--------+
|  ID    |  aaa   |  bbb   |
+--------+--------+--------+
|  23    | value1 | value2 |    <----copy this row

d2:

+--------+--------+--------+--------+
|  ID    |  ccc   |  bbb   |  aaa   |
+--------+--------+--------+--------+
|  23    |        | value2 | value1 |       <----I need this result

but this code:

string rowID=23;
DataRow[] result = dt1.Select($"ID = {rowID}");
dt2.Rows.Add(result[0].ItemArray);

gives:

d2:

+--------+--------+--------+--------+
|  ID    |  ccc   |  bbb   |  aaa   |
+--------+--------+--------+--------+
|  23    | value1 | value2 |        |    <---- :( NOT what I need
Devy
  • 703
  • 6
  • 17

1 Answers1

0

I think this is your homework, but here you have some simple and not very smart solution:

private DataTable DTCopySample()
{
    int cnt = 0;

    DataTable dt1 = new DataTable();
    dt1.Columns.Add("ID");
    dt1.Columns.Add("aaa");
    dt1.Columns.Add("bbb");

    DataTable dt2 = new DataTable();
    dt2.Columns.Add("ID");
    dt2.Columns.Add("ccc");
    dt2.Columns.Add("bbb");
    dt2.Columns.Add("aaa");

    dt1.Rows.Add();
    dt1.Rows[0]["ID"] = "23";
    dt1.Rows[0]["aaa"] = "val1";
    dt1.Rows[0]["bbb"] = "val2";

    dt1.Rows.Add();
    dt1.Rows[1]["ID"] = "99";
    dt1.Rows[1]["aaa"] = "val99";
    dt1.Rows[1]["bbb"] = "val98";

    string colName = string.Empty;

    foreach (DataRow row in dt1.Rows)
    {
        dt2.Rows.Add();

        foreach (DataColumn col in dt1.Columns)
        {
            dt2.Rows[cnt][col.ColumnName] = row[col.ColumnName].ToString();
        }

        cnt++;
    }

    return dt2;
}

There are more smart and better solutions, but this is fast-written (2 mins) and works. Remeber, that you have not specified columns datatypes or anything else, so I assumed there are strings everywhere for creating simple sample.

Maciej S.
  • 752
  • 10
  • 22