intrigued_66
intrigued_66

Reputation: 17248

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();
test.Columns.Add("Col1");
test.Columns.Add("Col2");
test.Columns.Add("Col3");
test.Columns.Add("Col4");

//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

Upvotes: 0

Views: 12973

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460138

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];
test.Rows.Add(row);

params C#

Upvotes: 5

Dima
Dima

Reputation: 1761

test.Rows.Add adds existing DataRow object to your table. First you have to create new row, then fill it with your data, and after that - add it to your data table. Here is the code in VB, it is easy, so you will be able to translate it to C# :)

Dim t As New DataTable
Dim r As DataRow
r = t.NewRow()
r.ItemArray = testObject
t.Rows.Add(r)

Upvotes: 2

Marshal
Marshal

Reputation: 6651

I think you are trying to add 4 rows(array) to 4 columned table.

It should be logically:

DataRow newRow = test.NewRow();

newRow [0] = testObject[0];
newRow [1] = testObject[1];
newRow [2] = testObject[2];
newRow [4] = testObject[3];

test.Rows.Add(newRow );

You can also pass in an object array as well, like so:

DataTable dt = new DataTable();
dt.Clear();
dt.Columns.Add("Name");
dt.Columns.Add("Marks");
object[] o = { "Ravi", 500 };
dt.Rows.Add(o);

Or even:

dt.Rows.Add(new object[] { "Ravi", 500 });

Upvotes: 2

Related Questions