Datatable Addition to Dataset exception
DataSet ds = DAL.GetData();
DataSet dsInvitee = null;
DataTable dt = ds.Tables[0].Copy();
IEnumerable<DataRow> q1 = dt.AsEnumerable().Skip(5).Take(10);
dsInvitee = new DataSet();
DataTable dtNew = new DataTable();
dtNew.TableName = "DTInv";
dtNew = q1.CopyToDataTable<DataRow&g开发者_如何学Got;();
dsInvitee.Tables.Add(dtNew.Copy());
dsInvitee.AcceptChanges();
dtNew = null;
dtNew = new DataTable();
dtNew.TableName = "DTTags";
dtNew = ds.Tables[1].Copy();
dsInvitee.Tables.Add(dtNew.Copy());
I am getting error in the last line as "A DataTable named 'Table1' already belongs to this DataSet."... Please help.
Your issue is because of the line dtNew = q1.CopyToDataTable<DataRow>();
, because the CopyToDataTable
extension method:
Returns a DataTable that contains copies of the DataRow objects, given an input IEnumerable object where the generic parameter T is DataRow.
This means that the table name of "DTInv" gets blown away as after the call to CopyToDataTable, dtNew
no longer refers to the same DataTable
. Move the dtNew.TableName = "DTInv";
to after the call to CopyToDataTable
:
DataTable dtNew = new DataTable();
dtNew = q1.CopyToDataTable<DataRow>();
dtNew.TableName = "DTInv";
dsInvitee.Tables.Add(dtNew.Copy());
dsInvitee.AcceptChanges();
I think the problem is with the second to last row. You are overwriting the instance dtNew. Everything you did so far with that instance is lost and it is assigned a table from the original dataset and that's what you are adding to the data set in the last row...
Based on what Daniel has said above, try swapping the order of the
dtNew.TableName = "DTTags";
and the
dtNew = ds.Tables[1].Copy();
lines around.
精彩评论