GeekZilla
"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); } }
Once I'd found the solution to this problem it made perfect sense.
If you've just got this error, I hope this helped you out.
Time for a
A self confessed Microsoft bigot, Paul loves all Microsoft products with a particular fondness for SQL Server. Paul is currently focusing on Web 2.0 patterns and practices and is always looking for better ways of doing things.
I love the .net platform, and I find it to be the most productive toolset I have used to date.
Comments
Bizu said:
Thks !!
The solution was so easyyyyy....
reza said:
yes.but by this soloution instead of added rowstate we will have modefied state
sa_keles said:
thanks Paul it was very helpful for me
sindia said:
thanks a lot
Aki said:
Thanks ! worked perfectly!
Alex said:
Thanks a lots Paul. It solved my problem. _
Nasim said:
Hey it worked.. thanks..
susanta said:
Thank you very much,it is very use full for me
Ajay said:
Thanks a lot Paul...really a very good solution...solved my problem...
Mandeep said:
Good Work!
Amani said:
Hey guys,
I have the same problem but with columns instead.. I want to build a datatable that contains only a subset of columns of another datatable. Is there a function similar to clone that works with columns
DataTable FeatK1 = new DataTable();
DataColumn intID= TableIntSub.Columns["IntID"]; DataColumn dc1 = TableIntSub.Columns[featureName + '1']; DataColumn dc2 = TableIntSub.Columns[featureName + '2']; FeatK1.Columns.Add(intID);--> THIS IS WHERE THE ERROR STARTS FeatK1.Columns.Add(dc1); FeatK1.Columns.Add(dc2);
Vinoth said:
Thanks buddy..great work..really helpful..
Vinoth said:
Thanks buddy..great work..really helpful..
Tom said:
Thanks, worked for me too!
Werner said:
Another way is to use the ToArray property of the DataRow object and feed the to the DataTable.Rows.Add method:
newTable.Rows.Add(originalRow.ToArray);
Screecher said:
Many thanks - Nice little solution to a pesky error And you're right - Does make sense once you see it
Gopinath said:
Thank you..................Very very much paul, Short and strong stuff.
Pandex said:
Thanks was so hellful, great solution
Matt Hunter said:
Thank you so much! I was getting pretty frustrated!
Vinh said:
You're awesome!!!
Vikram said:
Thanks a lot,
It solved my problem that was struked for a long time
Thanks again
DeepDreams said:
Thanks a lot. It really help me. I already got this problem for so long, and the solution is very easy. Once again thanks a lot.
TableNoob said:
Hi
I normally don't post comments on peoples sites. But, I want to thank you for saving me heaps of time trying to figure this out. I knew there would be an easy solution to my problem and your's was it !!!
Cheers
TableNoob
Levanter30 said:
Thanks! This is exactly what i needed
dannyc said:
good work man, thanks!
Ali said:
Thanks buddy!!
Jules said:
So many "thanks", here's another
Crappy said:
Just copied and paste the error in, it seems so many people have the same kinda programming style. Clearly Microsoft didnt want to do it this way. Awsome man, Cheers.
Naveen Kumar M said:
Your help is soooo nice like u..........!
SparkyRoosta said:
AWESOME! Thanks for that!
Gotta love GoogleMagic!
Intellect India said:
Excellent..Tnx Paul!
myro said:
thx!!!
Arturomar said:
Just thanks, thanks, very much.
lalitha said:
Thanks a lot ,ur solution is very easy and so simple
itsme said:
Its working fine thanx.
Lynn said:
Doesn't seem to work on VS 2003/ADO.Net 1.0. 'System.Data.DataRowCollection' does not contain a definition for 'Import'. Darn it! It was such a nice, neat workaround, too.
Azarue said:
10x for the solution, i wonder if you find any reference at the msdn.
nj said:
if same schema u can use dt_tmp.Rows.Add(row.ItemArray); work for me
Sid said:
Thanks, This is just the solution I was looking for
Rania Nazmey said:
Really helpfull. i applied it in my code
Thanks alot
Benjamin said:
Thanks alot Paul.
if i wanted to add the nex 48 row how can i do it programmatically...
I use this to get it, but kinda of weird..is it a normal practice?
StreamReader dataStream = File.OpenText(Server.MapPath(@"Data/data.txt"));
int i =0; int count = 0; bool found = false; try { DataTable dt = CsvParser.Parse(dataStream,false); DataTable dtNew = new DataTable(); dtNew = dt.Clone(); foreach (DataRow dRow in dt.Rows) { i++; if(ddMeterId.SelectedValue.Equals(dRow["Column1"].ToString())) { found = true; } if(found) { dtNew.ImportRow(dRow); count++; if(count==49) break; } } ReadingList.DataSource = dtNew; ReadingList.DataBind(); } catch(Exception ex) { Response.Write(ex.Message); } finally { if(dataStream!= null) dataStream.Close(); }
marshp3 said:
You can take rows and skip rows programatically using LINQ
var d = from c in dt
select c;
d.Take(48);
Any questions skype me
David said:
How can i sort table. when i try to use table.defaultview.sort="", it not work. any help?
marshp3 said:
To Sort a default view using the sort property you need to specify a field and this defaults to ASC unless you specify DESC
e.g
DefaultView dv = table.DefaultView;
dv.Sort = "FIELD1 DESC";
Dy Oswald said:
hi paul,
didn't realize I could use ImportRow() method instead of trying to add a new row in rowcollection )
this sure saves me a heck of frustrations
thx man!
Radhika said:
thanks a lot...
it worked!!!
sreenup_mca2004@yahoo.co.in said:
Thanks Paul
Janssen said:
Thanks my friend,
It solved my problem.
I was very frustrated for a long time
Thanks again from Costa Rica...
.net fever said:
working like a charm !! Thanks a lot man
kougar said:
Thanks for the easy answer bro.
KK said:
I got the exact same error and your post saved my day! . Thanks a lot!
w said:
what about DataTableExtensions..::.CopyToDataTable<(Of <(T>> Method ?
Brian said:
Awesome job, Paul. You are my new hero.
Abel said:
Your post is still helping developers even though it was posted more than one year ago.
Thanks,
Tony said:
I had the same problem and this solution worked perfectly. It kept me from jumping off the roof of our building. Thanks
Guy R. said:
Thank you so much for giving me the option to go to bed when it is still dark outside... no doubt, the best post i have ever seen on the net.
Son Trung said:
I struggled this for all day long. You've helped me save a lot of time! Thanks!
z3r0c001 said:
Thanks, this was the first result on google and was exact solution.
GG said:
Thanks man!!!
dt_tmp.Rows.Add(row.ItemArray);
The above way does not work in C# as far as I know...
Tuhin said:
Thanks
EJR said:
Thanks so much for taking the time to post this solution
Ernesto said:
Thanks, Paul. Worked like a charm!
Linna said:
Thanks! It solved my problem!
ASPNewbie said:
Hey, Was stuck with this annoying issue for such a long time! Dint know the resolution wud be so simple!
Thanks for the solution.!! Keep up the good work!
susmita said:
thanks alot!! it worked!!!
K said:
Great solution thanks!
Tejaswini said:
Thanks it helped me too
Tsuo Kang Chen said:
Thank you. You are absolutely right about the "columns".
Manish said:
Thanks a Lot Paul
3xplod3 said:
Thanks Paul.. very useful solution
Vinayak said:
dt2.Rows.Add(dt1.ItemArray) should also work for the above problem.
Ishwar Rajpurohit said:
Thanks a lot for nice solution
Atul chauhan said:
Hey Paul, Thanks this solution has solved my problem
wawaba said:
Thanks man! Also helped here!
An ASP.NET user said:
Thanks. This saved me 10 minutes of frustration.
<a href="http://windows-linux-admin.blogspot.com">C# and jQuery tips</a>
Surya said:
The Solution is simple.. Yet Powerful.... Thanks a lot..
Vinodh said:
Thanks a lot. That saved me a lot of time.
Abdel said:
Thank you very much Paul
Andrew said:
When I tried to update the table with the newly imported rows to a MS Access database the changes do not show up, do you know off the top of your head what could be some reasons?
Thanks!
said:
great info...keep doing the great work
Frank said:
Thanks once again!!
67patrol said:
Thanks Paul, saved me so much time!
Allen said:
Great article, but if anyone is using a List(of DataRow) object to begin with, then the simplest solution is as follows:
Dim lstResults As New List(of DataRow)
'... Code to populate 1...n rows in object above
'Now in single line using Extension method, copy to DataTable
Dim myDataTable As DataTable = lstResults.CopyToDataTable()
Charles said:
Cheers buddy! Worked perfectly
MaiT said:
Cheers mate.
nuwan said:
thanks
Roy said:
Wonderful!
jisaw said:
worked perfectly
Inge said:
I put the error into Google search and this was the first result - it perfectly solved my problem. That happens far too rarely!
This solution was posted in 2006 and is still saving people grief! Thank you!
Thanuj K said:
Thnx!! it is working fine.
kabibi said:
Thanks !
kabibi said:
Thank you so much !!!
Mark said:
Helped so much. Thanks for posting.
siv said:
Nice solution
Ali said:
Great help, sorted issue for me as well. Thanks
Jalal khan said:
thank sir it is working fine
Hemant said:
Thaks lot Paul.
Straton said:
Thanks Paul, it working fine
Julian said:
Thanks Paul, very helpful
Les said:
Thank you. A clear explanation and a simple solution. I looked at several reponses to this problem and found the usual - people commenting for the sake of showing how smart they are without providing a solution. One idiot even ignored the fact that the problem was importing a column schema and prattled on about using .ImportRow!!
Mike said:
I am very happy to be part of your life! you're amazing. hehe