Can't add DataRow to DataTable
Can't add DataRow to DataTable
(OP)
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?
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?
RE: Can't add DataRow to DataTable
I'm using this in one of my standard libraries without any problems. .NET 2.0.
CODE --> C#
You could always try this instead when adding the row to the table:
CODE --> C#
and see if that works.
RE: Can't add DataRow to DataTable
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.
RE: Can't add DataRow to DataTable
RE: Can't add DataRow to DataTable
<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