This Row already belongs to another table error when trying to add rows?
回答1
You need to create a new Row
with the values from dr
first. A DataRow
can only belong to a single DataTable
.
You can also use Add
which takes an array of values:
myTable.Rows.Add(dr.ItemArray)
Or probably even better:
// This works because the row was added to the original table.
myTable.ImportRow(dr);
// The following won't work. No data will be added or exception thrown.
var drFail = dt.NewRow()
drFail["CustomerID"] = "[Your data here]";
// dt.Rows.Add(row); // Uncomment for import to succeed.
myTable.ImportRow(drFail);
回答2,重点是用ImportRow这个方法
Try this:
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = dt.Clone();
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
dtSpecificOrders.ImportRow(dr);
}
回答3
yourTable.ImportRow(dataRow);
It's because the row you're copying doesn't have the same TableName
:
For example, try:
Table1.TableName = "Table1";
Table2.TableName = "Table2";