C# – Adding data to datatable using object[] not working


The Add method for a DataTable contains an overload for adding data to a table using an object array.

I would like to have an array of arrays, which I can loop through and insert into the DataTable. The code below creates an array of size 4000 and puts an array of 4 "columns" into the 0th element of the outer array (ContiguousTradeMem).

However, when I debug the last line below all the data which was in testObject (and in the cache- ContiguousTradeMem[]) does not get copied over to the DataTable()???

//The "array" which we wish to insert into the DataTable
object[] testObject = new object[4];

//Inserts some test data
for (int m = 0; m < 4; m++)
    testObject[m] = "test";

//A test DataTable
DataTable test = new DataTable();

//Put the test "array" into the cache
ContiguousTradeMem[0] = testObject; //The data of testObject is fine here

//Write the cache element to the DataTable
test.Rows.Add(ContiguousTradeMem[0]); //The data is not fine in test.Rows

Best Solution

Actually the overload of DatarowCollection.Add takes a param array which is similar to a list of paramaters. You can initialize and add the DataRow from your array in this way:

var row = test.NewRow();
row.ItemArray = (Object[])ContiguousTradeMem[0];

params C#

Related Question