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

后端 未结 7 1486
闹比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:18

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

    0 讨论(0)
  • 2020-11-28 03:20

    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);
    }
    
    0 讨论(0)
  • 2020-11-28 03:20

    Why don't you just use CopyToDataTable

    DataTable dt = (DataTable)Session["dtAllOrders"];
    DataTable dtSpecificOrders = new DataTable();
    
    DataTable orderRows = dt.Select("CustomerID = 2").CopyToDataTable();
    
    0 讨论(0)
  • 2020-11-28 03:27

    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);
    
    0 讨论(0)
  • 2020-11-28 03:28
    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";
    
    0 讨论(0)
  • 2020-11-28 03:37
    foreach (DataRow dr in dtSpecificOrders.rows)
    {
       dtSpecificOrders.Rows.Add(dr.ItemArray); 
    }
    
    0 讨论(0)
提交回复
热议问题