我有一个DataTable,它有一些行,我使用select来过滤行以获取DataRows的集合,然后我使用foreach循环并将其添加到另一个DataTable,但它给了我错误"This Row已经属于到另一张桌子".这是代码:
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.
}
Run Code Online (Sandbox Code Playgroud)
Jos*_*rke 323
您需要Row使用第一个值创建一个新的dr.A DataRow只能属于一个DataTable.
您还可以使用Add带有一组值的数据:
myTable.Rows.Add(dr.ItemArray)
Run Code Online (Sandbox Code Playgroud)
或者甚至更好:
// 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);
Run Code Online (Sandbox Code Playgroud)
小智 28
试试这个:
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = dt.Clone();
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
dtSpecificOrders.ImportRow(dr);
}
Run Code Online (Sandbox Code Playgroud)
yourTable.ImportRow(dataRow);
Run Code Online (Sandbox Code Playgroud)
这是因为你要复制的行不一样TableName:
例如,尝试:
Table1.TableName = "Table1";
Table2.TableName = "Table2";
Run Code Online (Sandbox Code Playgroud)