Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Can't add DataRow to DataTable

Status
Not open for further replies.

gib99

Programmer
Mar 23, 2012
51
CA
Hello,

I'm having trouble adding a DataRow to a DataTable.

I create the DataRow like so:

DataRow row = myDataTable.NewRow();

I add things to the row, then I try to add the row back to the table:

myDataTable.Rows.Add(row);

It tells me: "This row already belongs to this table."

Ironically, if I try:

row.AcceptChanges();

it tells me: "Cannot perform this operation on a row not in the table."

so is it in the table or is it not?

myDataTable.AcceptChanges() seems to run without any exceptions, but my table is still empty.

What gives?
 
Do you have a primary key set on the table? If you do, you could have a duplicate.

I'm using this in one of my standard libraries without any problems. .NET 2.0.

Code:
[COLOR=#2B91AF]DataRow[/color] tempRow;
[COLOR=#0000FF]while[/color] (DbDataReader.Read())
{
    tempRow = tempTable.NewRow();
    [COLOR=#0000FF]for[/color] ([COLOR=#0000FF]int[/color] i = 0; i < DbDataReader.FieldCount; i++)
        tempRow[i] = DbDataReader[i];
    tempTable.Rows.Add(tempRow);
}
[COLOR=#0000FF]return[/color] tempTable;

You could always try this instead when adding the row to the table:

Code:
myDataTable.ImportRow(row);

and see if that works.
 
Thanks Moregelen,

I solved the problem by adding the row right after creating it.

At first, I had this:

DataRow row = myDataTable.NewRow();
row[1] = x;
row[2] = y;
row[3] = z;
myDataTable.Rows.Add(row);

But now I have this:

DataRow row = myDataTable.NewRow();
myDataTable.Rows.Add(row);
row[1] = x;
row[2] = y;
row[3] = z;

The latter seems to work.
 
Solution 1:
<code>
DataRow row = dt.NewRow();
row[0] = "maria";
row[1] = "george";
dt.Rows.Add(row);
// row = dt.NewRow();
row[0] = "Helene";
row[1] = "Maxim";
dt.Rows.Add(row);
</code>
Running the above you get ""This row already belongs to this table."
Uncomment the comments and the second row is added.
Reason: In fact
<cde>
row[0] = "Helene";
row[1] = "Maxim";
</code>
modify the previous values of the same "row" object.

Solution 2:
<code>
DataRow row = dt.NewRow();
row[0] = "maria";
row[1] = "george";
dt.Rows.Add(row); // or dt.ImportRow(row);
row[0] = "Helene";
row[1] = "Maxim";
dt.ImportRow(row);

row[0] = "Christina";
row[1] = "Bill";
dt.ImportRow(row);
</code>
Explanation:
Rows.Add(dr) - add a reference of te dr DataRow object
Rows.ImportRow(dr) - add a copy of the dr DataRow object

obislavu




 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top