我有一个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.
}
答案 0 :(得分:314)
您需要先使用Row
的值创建新的dr
。 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);
答案 1 :(得分:26)
试试这个:
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = dt.Clone();
DataRow[] orderRows = dt.Select("CustomerID = 2");
foreach (DataRow dr in orderRows)
{
dtSpecificOrders.ImportRow(dr);
}
答案 2 :(得分:8)
yourTable.ImportRow(dataRow);
这是因为你要复制的行没有相同的TableName
:
例如,尝试:
Table1.TableName = "Table1";
Table2.TableName = "Table2";
答案 3 :(得分:3)
这不是最干净/最快/最简单/最优雅的解决方案,但它是我为在类似情况下完成工作而创建的强力解决方案:
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中的名称必须与原始表中的名称相匹配才能生效。我刚用过&#34; ID&#34;和&#34;姓名&#34;作为例子。
答案 4 :(得分:2)
foreach (DataRow dr in dtSpecificOrders.rows)
{
dtSpecificOrders.Rows.Add(dr.ItemArray);
}
答案 5 :(得分:1)
为什么不使用CopyToDataTable
DataTable dt = (DataTable)Session["dtAllOrders"];
DataTable dtSpecificOrders = new DataTable();
DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();
答案 6 :(得分:0)
您可以为列提供一些ID并将其命名为唯一。