Row already belongs to another table
.NET, ADO.NET | Nauman | November 1, 2009 at 8:12 amWhen copying a row from one datatable to another you might get the error "this row already belongs to another table".
Typically you might write code like this:
string sConnString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;DataSet ds = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(sConnString,CommandType.Text,"select * from suppliers order by supplierid");int nRowCount = 0;DataTable dt = ds.Tables[0];DataTable dt2 = dt.Clone();dt2.Clear();foreach (DataRow row in dt.Rows){dt2.Rows.Add(row);nRowCount++;if (nRowCount == 10){DataRow rowNew = dt2.NewRow();rowNew["supplierid"] = -12345;dt2.Rows.Add(rowNew);nRowCount = 0;}}
The correct way is instead to "import" the row using ImportRow
Tags: ADO.NET, asp.net, datarow, datatable, rowsstring sConnString = ConfigurationManager.ConnectionStrings["NorthwindConn"].ConnectionString;DataSet ds = Microsoft.ApplicationBlocks.Data.SqlHelper.ExecuteDataset(sConnString,CommandType.Text,"select * from suppliers order by supplierid");int nRowCount = 0;DataTable dt = ds.Tables[0];DataTable dt2 = dt.Clone();dt2.Clear();foreach (DataRow row in dt.Rows){dt2.ImportRow(row);nRowCount++;if (nRowCount == 10){DataRow rowNew = dt2.NewRow();rowNew["supplierid"] = -12345;dt2.Rows.Add(rowNew);nRowCount = 0;}}



Tweet This
Digg This
Save to delicious
Stumble it