试图添加行时,此行已经属于另一个表错误?

我有一个DataTable有一些行,我使用select过滤行以获得DataRows集合,然后通过使用foreach循环,并将其添加到另一个DataTable,但它给我的错误“此行已属于到另一张桌子“。 这里是代码:

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创build一个新的Row 。 一个DataRow只能属于一个DataTable

你也可以使用Add来获得一个值的数组:

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

尝试这个:

 DataTable dt = (DataTable)Session["dtAllOrders"]; DataTable dtSpecificOrders = dt.Clone(); DataRow[] orderRows = dt.Select("CustomerID = 2"); foreach (DataRow dr in orderRows) { dtSpecificOrders.ImportRow(dr); } 
 yourTable.ImportRow(dataRow); 

这是因为你正在复制的行不具有相同的TableName

例如,尝试:

 Table1.TableName = "Table1"; Table2.TableName = "Table2"; 
 foreach (DataRow dr in dtSpecificOrders.rows) { dtSpecificOrders.Rows.Add(dr.ItemArray); } 

这不是最干净/最快捷/最简单/最优雅的解决scheme,但是我创build了一个强大的工具来完成类似的工作:

 DataTable dt = (DataTable)Session["dtAllOrders"]; DataTable dtSpecificOrders = new DataTable(); // Create new DataColumns for dtSpecificOrders that are the same as in "dt" DataColumn dcID = new DataColumn("ID", typeof(int)); DataColumn dcName = new DataColumn("Name", typeof(string)); dtSpecificOrders.Columns.Add(dtID); dtSpecificOrders.Columns.Add(dcName); DataRow[] orderRows = dt.Select("CustomerID = 2"); foreach (DataRow dr in orderRows) { DataRow myRow = dtSpecificOrders.NewRow(); // <-- create a brand-new row myRow[dcID] = int.Parse(dr["ID"]); myRow[dcName] = dr["Name"].ToString(); dtSpecificOrders.Rows.Add(myRow); // <-- this will add the new row } 

DataColumns中的名称必须与原始表中的名称匹配。 我只是用“ID”和“Name”作为例子。

你为什么不使用CopyToDataTable

 DataTable dt = (DataTable)Session["dtAllOrders"]; DataTable dtSpecificOrders = new DataTable(); DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable(); 

你可以给一些id给列,并命名它的唯一。