尝试添加行时,该行已属于另一个表错误? [英] This Row already belongs to another table error when trying to add rows?

查看:86
本文介绍了尝试添加行时,该行已属于另一个表错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些行的DataTable,我正在使用select过滤行以获取DataRows的集合,然后我通过使用foreach循环遍历并将其添加到另一个DataTable中,但这给了我错误行已属于另一个表。下面是代码:

I have a DataTable which has some rows and I am using the select to filter the rows to get a collection of DataRows which I then loop through using foreach and add it to another DataTable, but it is giving me the error "This Row already belongs to another table". Here is the code:

DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();

DataRow[] orderRows = dt.Select("CustomerID = 2");

foreach (DataRow dr in orderRows)
{
    dtSpecificOrders.Rows.Add(dr); //Error thrown here.
}


推荐答案

您需要创建一个新的,其值首先来自 dr DataRow 只能属于单个 DataTable

You need to create a new Row with the values from dr first. A DataRow can only belong to a single DataTable.

您还可以使用 Add 接受一个值数组:

You can also use Add which takes an array of values:

myTable.Rows.Add(dr.ItemArray)

或者甚至更好:

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

这篇关于尝试添加行时,该行已属于另一个表错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆