Insert New Row into Existing DataTable Big Problem .. Please help !!!

K

Kelvin

Hi All,

I have to the following problem on add new row into existing DataTable
while the DataTable Looping.


for (i=0; myTable.Rows.Count > i ; i++ )
{
DataRow dataRow = myTable.Rows;
dataRow["Stockroom"] = "";
dataRow["CurrencyCode"] = "";
dataRow["TotalPrice"] = mySubTotal;
myTable.Rows.Add(dataRow); <------
}

DetailGrid.DataSource = myTable;

It display the following error message :
"Exception Details: System.ArgumentException: This row already belongs
to this table."
 
P

paracio

Hi kelvin,
if want to add new row into datatable, used DataTable.NewRow()
Change your code like bellow :
DataRow dataRow = myTable.NewRow(); <--created new row
dataRow["Stockroom"] = "";
dataRow["CurrencyCode"] = "";
dataRow["TotalPrice"] = mySubTotal;
myTable.Rows.Add(dataRow); <-- add datarow into datatable

and also you need acceptchanges.

Regards,
~paracio~
 
H

Hans Kesting

Kelvin said:
Hi All,

I have to the following problem on add new row into existing DataTable
while the DataTable Looping.


for (i=0; myTable.Rows.Count > i ; i++ )
{
DataRow dataRow = myTable.Rows;


here you get a *reference* to an existing row "i" from the table ...
dataRow["Stockroom"] = "";
dataRow["CurrencyCode"] = "";
dataRow["TotalPrice"] = mySubTotal;

.... then you alter data ...
myTable.Rows.Add(dataRow); <------

.... and then you try to add the row again (= a second time) ...
}

DetailGrid.DataSource = myTable;

It display the following error message :
"Exception Details: System.ArgumentException: This row already belongs
to this table."

.... so this error is entirely right.

As you got a *reference* to the row, this is still a row that is present
in the table, not a new (independant) copy. Therefore you don't need
to "add it back" as it never left the table.
If you want to add a new row, you can use the NewRow() method on
the table. This returns an empty row that you can fill. This new row you must
add to that table.

Hans Kesting
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top