This Row already belongs to another table error when trying to add rows?

匿名 (未验证) 提交于 2019-12-03 08:52:47

问题:

I have a DataTable which has some rows and I am using the select to filter the rows to get a collection of DataRows which I then loop through using foreach and add it to another DataTable, but it is giving me the error "This Row already belongs to another table". Here is the code:

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

回答1:

You need to create a new Row with the values from dr first. A DataRow can only belong to a single DataTable.

You can also use Add which takes an array of values:

myTable.Rows.Add(dr.ItemArray) 

Or probably even better:

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


回答2:

Try this:

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


回答3:

yourTable.ImportRow(dataRow); 

It's because the row you're copying doesn't have the same TableName:

For example, try:

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


回答4:

This isn't the cleanest/quickest/easiest/most elegant solution, but it is a brute force one that I created to get the job done in a similar scenario:

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

The names in the DataColumns must match those in your original table for it to work. I just used "ID" and "Name" as examples.



回答5:

foreach (DataRow dr in dtSpecificOrders.rows) {    dtSpecificOrders.Rows.Add(dr.ItemArray);  } 


回答6:

Why don't you just use CopyToDataTable

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


回答7:

you can give some id to the columns and name it uniquely.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!