0

I'm trying to add a new column to an already existing DataTable using c#.

The best I could do is to actually copy each DataRow as explained in here and here but with no success since those answers specifically say that both DataTable must have the same columns. Whenever I try to add any kind of value to the new column (which is at the end of a new DataTable named dt I'm left with a DataTable with the same number of rows but no values at all.

foreach (DataRow dr in ret.Rows)
{
    dt.Rows.Add(dr.ItemArray, "1");
}

ret is a DataTable with X columns and N Rows.

dt is a DataTable with X+1 columns and N Rows.

Community
  • 1
  • 1
Miquel Coll
  • 759
  • 15
  • 49

1 Answers1

1

This should work as desired:

foreach (DataRow dr in ret.Rows)
{
    DataRow row = dt.Rows.Add();
    for (int i = 0; i < dr.ItemArray.Length; i++)
        row.SetField(i, dr.ItemArray[i]);
    row.SetField(dt.Columns.Count - 1, "1");
}

Another approach is to assign a DefaultValue to the last column since you're using always the same constant value:

dt.Columns[dt.Columns.Count - 1].DefaultValue = "1";

Now you don't need to provide this value. You can use DataTable.Merge:

dt.Merge(ret);
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • yep. That did it. I'm a little worried about the performance I might get but It works. Thanks! – Miquel Coll Feb 15 '16 at 16:12
  • @MiquelColl: performance is not an issue. All .NET methods like `DataTable.ImportRow` use similar loops but with additional overhead. – Tim Schmelter Feb 15 '16 at 16:14
  • @MiquelColl: but there was a bug, i used `dr.SetField` instead of `row.SetField`. I've also provided another approach. – Tim Schmelter Feb 15 '16 at 16:17
  • I used the first code you provided row[i] which worked as well. Any difference with the setField? – Miquel Coll Feb 15 '16 at 16:19
  • There's no Default Value, I was just putting a 1 in there in order to reduce the complexity of the question. Thanks regardless! – Miquel Coll Feb 15 '16 at 16:21
  • @MiquelColl: ok, maybe it's helpful for others. `SetField` is a similar way to the indexer but it comes into handy with nullable types. – Tim Schmelter Feb 15 '16 at 16:21