locked
Strange DataRow.ItemArray.CopyTo behavior RRS feed

  • Question

  • Does anyone have any idea why this occurs?  I have two DataTables both identically defined.  When I copy a DataRow from one using method 1 (see below) I get an empty DataRow.  When I use method 2 I get an exaxt copy:

     

    Method 1

    DataRow drow = dtable2.NewRow();

    dtable1.Rows[0].ItemArray.CopyTo(drow.ItemArray, 0);

    dtable2.Rows.Add(drow);

     

    Method 2

    DataRow drow = dtable2.NewRow();

    object[] itemArray = new object[dtable1.Columns.Count];

    dtable1.Rows[0].ItemArray.CopyTo(itemArray, 0);

    drow.ItemArray = itemArray;

    dtable2.Rows.Add(drow);

     

    It seems very strange to me that I'd have to utilize that object array.  And yes I'm well aware there are other ways to accomplish this (ImportRow for example) but I'm more curious why Method 1 is producing no exceptions, creating a record but simply not copying the data.

     

    Thanks for any input you might have,

     

    Dane R. Vinson

    Friday, April 27, 2007 5:12 PM

Answers

  • The ItemArray property returns a new array with copies of all of the values in the row. Setting values in this array has no effect on the row. However, when you set the value of ItemArray to an array instance, the values of the new array are copied into the DataRow.

     

    It seems like this is a case where Get/Set methods would have been more appropriate than a property, since it doesn't really follow property semantics. But that ship has sailed.

    Friday, April 27, 2007 6:07 PM

All replies

  • The ItemArray property returns a new array with copies of all of the values in the row. Setting values in this array has no effect on the row. However, when you set the value of ItemArray to an array instance, the values of the new array are copied into the DataRow.

     

    It seems like this is a case where Get/Set methods would have been more appropriate than a property, since it doesn't really follow property semantics. But that ship has sailed.

    Friday, April 27, 2007 6:07 PM
  • Hi all, I just want to drop a note to thank the question and answer.  I was scratching my head for the exact strange behavior.
    hz
    Friday, September 25, 2009 6:05 PM
  • Thanks very much, I got this problem today. 

    David A Nelson, just talked about the point. He is perfectly right.

    Wednesday, December 28, 2016 6:34 AM
  • Just skip Copy and do like:

    DataRow teste = this.rFComDataSet.TestStepNames.NewRow();
    teste.ItemArray = row.ItemArray;

    row.ItemArray will create a new object for you.

    Tuesday, June 11, 2019 5:34 PM