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.
}
From stackoverflow
-
You need to create a new row with the values from dr first. A DataRow can only belogn to a single data table.
You can also use the method which takes an array of values so you would do:
myTable.Rows.Add(dr.ItemArray)Edit
Probally even better you could do:
myTable.ImportRow(dr);Xaisoft : Can I use ImportRow as an alernative? and Why would .NET only not allow you to have the same DataRow for different DataTables? Is this by design?Jhonny D. Cano -Leftware- : I was about to suggest the sameXaisoft : Thanks for the above snippet. I was just about to ask if I had 100 rows, would I have to type all of them out?JoshBerke : Heh I just realized ImportRow, edit my answer and you all beat me to it. But yea I'd recommend that approach as it will copy the row for youXaisoft : If I do it the dr.ItemArray way, would I still need to create a NewRow?JoshBerke : Nope you shouldn't
0 comments:
Post a Comment