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

后端 未结 7 1487
闹比i
闹比i 2020-11-28 02:58

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 ano

相关标签:
7条回答
  • 2020-11-28 03:37

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

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

    0 讨论(0)
提交回复
热议问题