我有一个包含一些行的 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. }
您需要Row使用第一个值创建一个新值dr。ADataRow只能属于单个DataTable。
Row
dr
DataRow
DataTable
您还可以使用Addwhich 接受一组值:
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);