0

I want to copy first row of one DataTable to first row of another DataTable. I did as shown below but it throws error like

Property or indexer 'System.Data.DataRowCollection.this[int]' cannot be assigned to -- it is read only

DataTable dt = GetTable();
DataTable dt1 = GetTable1();
dt.Rows[0] = dt1.Rows[0];
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
peter
  • 8,158
  • 21
  • 66
  • 119
  • What does your `GetTable()` returns? – Thadeu Fernandes May 29 '18 at 16:59
  • @ThadeuFernandes It obviously returns a `DataTable` instance... – Camilo Terevinto May 29 '18 at 17:00
  • 1
    Possible duplicate of [C# simple way to copy or clone a DataRow?](https://stackoverflow.com/questions/12025012/c-sharp-simple-way-to-copy-or-clone-a-datarow) – Camilo Terevinto May 29 '18 at 17:01
  • Yes, it can be obvious, but more values other than a new instance can be assigned to `DataTable`, a new instance of `DataTable` will have it's row count equals 0, resulting in **out of range** exception during runtime or you may have a method where you already create rows with empty values in order to just fill them later, both will give you the same exception (dt.Row[0] is readonly) and are treated differently. Anyway, your collection of rows work like `IEnumerable`, the collection is readonly, you can either use `dt.Rows.Add (row)` or `dt.Rows.InsertAt (row, index)` to fill your collection. – Thadeu Fernandes May 29 '18 at 17:21

2 Answers2

0

You have to copy it field by field.

Sean Munson
  • 343
  • 2
  • 9
0

The data row within the datatable is immutable, which means that you can change the values of its fields, but not the object itself, being said that you should copy the values from you source row to the destination row.

Assuming your datatables have the same columns:

DataTable dt = GetTable();
DataTable dt1 = GetTable1();
foreach(DataColumn column in dt.Columns)
{
    dt.Rows[0][column] = dt1.Rows[0][column];
}

Hope this helps.

Elwi
  • 687
  • 1
  • 5
  • 15