2011年9月23日 星期五

This row already belongs to another table. Defining a Primary Key for a Table

Defining a Primary Key for a Table 
workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustID"]};
// Or
DataColumn[] columns = new DataColumn[1];
columns[0] = workTable.Columns["CustID"];
workTable.PrimaryKey = columns;

This row already belongs to another table.

"This row already belongs to another table" Error
What an annoying error!! I couldn't believe that I couldn't just add a Row from one DataTable to another, while looping around a DataTable's Rows.
It turned out to be slightly more complicated than the code I had written, I've simplified the code below from what I was actually doing in the loop, but you'll get the idea.
// This example generates the error
// ds is a dataset that has previously been populated
DataTable dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
foreach(DataRow row in dt1.Rows){
    if(row["Column1"] == 10){
        // This line generates the error...
        dt2.Rows.Add(row);
    }
}
The correct way to achieve this is to clone dt2 on dt1, this creates the appropriate columns, then when you want to copy the row from dt1 into dt2 you use the ImportRow Method.
// This example achieves the copy
// ds is a dataset that has previously been populated
DataTable dt1 = ds.Tables[0];
DataTable dt2 = new DataTable();
dt2 = dt1.Clone();
foreach(DataRow row in dt1.Rows){
    if(row["Column1"] == 10){
        // Import the Row into dt2 from dt1
        dt2.ImportRow(row);
    }
}

程式碼工作室
ERP/EIP/CMS/CHART/REPORT/SPC/EDA/雲端 系統開發整合
ASP/PHP/JSP/ASP.NET 網頁設計
技術指導顧問
信箱:paulwu0114@gmail.com
http://www.coding.com.tw

沒有留言:

張貼留言