我有一个数据表,其中有一些行,我使用选择来过滤行,以获得一个DataRows的集合,然后我循环使用foreach,并将其添加到另一个数据表,但它给我的错误“这一行已经属于另一个表”。代码如下:

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.
}

当前回答

在遇到这种错误时,尤其是在绑定场景中,应该非常小心。这很可能表明您可能绑定到错误的数据表。

其他回答

尝试使用copy方法复制数据表 dt1 = dt.Copy();

然后使用Clear方法删除dt1中的所有行 dt1.Rows.Clear ();

然后重新开始导入

foreach (DataRow myRow in dt.Rows)
{
   dt1.ImportRow(myRow);
}
yourTable.ImportRow(dataRow);

这是因为你复制的行没有相同的TableName:

例如,试着:

Table1.TableName = "Table1";
Table2.TableName = "Table2";

您可以为列指定某个id,并唯一地命名它。

试试这个:

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

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

foreach (DataRow dr in orderRows)
{
    dtSpecificOrders.ImportRow(dr);
}

为什么不用CopyToDataTable呢

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

DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();