"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

Author Paul Marshall

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....

02/Feb/2007 10:30 AM

reza said:

yes.but by this soloution instead of added rowstate we will have modefied state

07/Feb/2007 08:49 AM

sa_keles said:

thanks Paul it was very helpful for me

28/Feb/2007 14:35 PM

sindia said:

thanks a lot

16/Mar/2007 05:38 AM

Aki said:

Thanks ! worked perfectly!

22/Mar/2007 17:10 PM

Alex said:

Thanks a lots Paul. It solved my problem. _

04/Apr/2007 02:32 AM

Nasim said:

Hey it worked.. thanks..

05/Apr/2007 11:17 AM

susanta said:

Thank you very much,it is very use full for me

23/Apr/2007 11:27 AM

Ajay said:

Thanks a lot Paul...really a very good solution...solved my problem...

27/Apr/2007 14:40 PM

Mandeep said:

Good Work!

12/May/2007 00:29 AM

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);
13/May/2007 00:53 AM

Vinoth said:

Thanks buddy..great work..really helpful..

16/May/2007 17:28 PM

Vinoth said:

Thanks buddy..great work..really helpful..

16/May/2007 17:36 PM

Tom said:

Thanks, worked for me too!

19/Jun/2007 05:16 AM

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);

20/Jun/2007 10:45 AM

Screecher said:

Many thanks - Nice little solution to a pesky error And you're right - Does make sense once you see it

28/Jun/2007 05:44 AM

Gopinath said:

Thank you..................Very very much paul, Short and strong stuff.

18/Jul/2007 13:08 PM

Pandex said:

Thanks was so hellful, great solution

20/Jul/2007 18:45 PM

Matt Hunter said:

Thank you so much! I was getting pretty frustrated!

21/Jul/2007 02:01 AM

Vinh said:

You're awesome!!!

13/Aug/2007 22:20 PM

Vikram said:

Thanks a lot,

It solved my problem that was struked for a long time

Thanks again

16/Aug/2007 16:32 PM

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.

21/Aug/2007 10:36 AM

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

04/Oct/2007 05:42 AM

Levanter30 said:

Thanks! This is exactly what i needed

11/Oct/2007 17:13 PM

dannyc said:

good work man, thanks!

26/Oct/2007 14:50 PM

Ali said:

Thanks buddy!!

12/Nov/2007 07:32 AM

Jules said:

So many "thanks", here's another

25/Nov/2007 22:59 PM

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.

04/Dec/2007 16:41 PM

Naveen Kumar M said:

Your help is soooo nice like u..........!

14/Dec/2007 04:55 AM

SparkyRoosta said:

AWESOME! Thanks for that!

Gotta love GoogleMagic!

18/Dec/2007 23:29 PM

Intellect India said:

Excellent..Tnx Paul!

18/Jan/2008 04:25 AM

myro said:

thx!!!

28/Jan/2008 13:50 PM

Arturomar said:

Just thanks, thanks, very much.

30/Jan/2008 20:55 PM

lalitha said:

Thanks a lot ,ur solution is very easy and so simple

11/Feb/2008 09:50 AM

itsme said:

Its working fine thanx.

15/Feb/2008 06:52 AM

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.

14/Mar/2008 20:58 PM

Azarue said:

10x for the solution, i wonder if you find any reference at the msdn.

31/Mar/2008 22:05 PM

nj said:

if same schema u can use dt_tmp.Rows.Add(row.ItemArray); work for me

21/Apr/2008 10:12 AM

Sid said:

Thanks, This is just the solution I was looking for

23/Apr/2008 14:25 PM

Rania Nazmey said:

Really helpfull. i applied it in my code

Thanks alot

24/Apr/2008 12:56 PM

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();
                        }
13/May/2008 07:41 AM

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

13/May/2008 10:28 AM

David said:

How can i sort table. when i try to use table.defaultview.sort="", it not work. any help?

02/Jun/2008 21:57 PM

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";

03/Jun/2008 22:23 PM

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!

19/Jun/2008 04:51 AM

Radhika said:

thanks a lot...

it worked!!!

19/Jun/2008 08:29 AM

sreenup_mca2004@yahoo.co.in said:

Thanks Paul

30/Jun/2008 13:03 PM

Janssen said:

Thanks my friend,

It solved my problem.

I was very frustrated for a long time

Thanks again from Costa Rica...

09/Jul/2008 07:55 AM

.net fever said:

working like a charm !! Thanks a lot man

10/Jul/2008 15:58 PM

kougar said:

Thanks for the easy answer bro.

27/Aug/2008 20:08 PM

KK said:

I got the exact same error and your post saved my day! . Thanks a lot!

04/Sep/2008 01:29 AM

w said:

what about DataTableExtensions..::.CopyToDataTable<(Of <(T>> Method ?

http://msdn.microsoft.com/en-us/library/bb396189.aspx

08/Sep/2008 02:18 AM

Brian said:

Awesome job, Paul. You are my new hero.

01/Oct/2008 20:57 PM

Abel said:

Your post is still helping developers even though it was posted more than one year ago.

Thanks,

08/Oct/2008 18:54 PM

Tony said:

I had the same problem and this solution worked perfectly. It kept me from jumping off the roof of our building. Thanks

15/Oct/2008 14:48 PM

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.

20/Nov/2008 19:05 PM

Son Trung said:

I struggled this for all day long. You've helped me save a lot of time! Thanks!

18/Mar/2009 10:08 AM

z3r0c001 said:

Thanks, this was the first result on google and was exact solution.

28/Mar/2009 01:50 AM

GG said:

Thanks man!!!

dt_tmp.Rows.Add(row.ItemArray);

The above way does not work in C# as far as I know...

22/May/2009 04:10 AM

Tuhin said:

Thanks

04/Jun/2009 13:40 PM

EJR said:

Thanks so much for taking the time to post this solution

21/Jul/2009 06:10 AM

Ernesto said:

Thanks, Paul. Worked like a charm!

06/Aug/2009 20:45 PM

Linna said:

Thanks! It solved my problem!

10/Sep/2009 19:10 PM

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!

18/Sep/2009 05:35 AM

susmita said:

thanks alot!! it worked!!!

21/Sep/2009 03:32 AM

K said:

Great solution thanks!

22/Sep/2009 11:31 AM

Tejaswini said:

Thanks it helped me too

23/Sep/2009 08:11 AM

Tsuo Kang Chen said:

Thank you. You are absolutely right about the "columns".

07/Oct/2009 15:24 PM

Manish said:

Thanks a Lot Paul

03/Nov/2009 11:14 AM

3xplod3 said:

Thanks Paul.. very useful solution

11/Nov/2009 19:11 PM

Vinayak said:

dt2.Rows.Add(dt1.ItemArray) should also work for the above problem.

22/Jan/2010 10:56 AM

Ishwar Rajpurohit said:

Thanks a lot for nice solution

15/Feb/2010 09:55 AM

Atul chauhan said:

Hey Paul, Thanks this solution has solved my problem

18/Feb/2010 06:56 AM

wawaba said:

Thanks man! Also helped here!

19/Mar/2010 17:22 PM

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>

31/Mar/2010 13:25 PM

Surya said:

The Solution is simple.. Yet Powerful.... Thanks a lot..

13/May/2010 13:15 PM

Vinodh said:

Thanks a lot. That saved me a lot of time.

21/May/2010 20:50 PM

Abdel said:

Thank you very much Paul

05/Jun/2010 11:01 AM

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!

20/Aug/2010 17:46 PM

said:

great info...keep doing the great work

20/Oct/2010 04:22 AM

Frank said:

Thanks once again!!

08/Nov/2010 16:51 PM

67patrol said:

Thanks Paul, saved me so much time!

22/Nov/2010 05:00 AM

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()

05/Jan/2011 18:40 PM

Charles said:

Cheers buddy! Worked perfectly

12/Jan/2011 10:27 AM

MaiT said:

Cheers mate.

28/Jan/2011 09:26 AM

nuwan said:

thanks

14/Feb/2011 06:38 AM

Roy said:

Wonderful!

28/Apr/2011 07:54 AM

jisaw said:

worked perfectly

04/May/2011 09:57 AM

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!

31/May/2011 14:58 PM

Thanuj K said:

Thnx!! it is working fine.

27/Jun/2011 09:32 AM

kabibi said:

Thanks !

17/Aug/2011 15:56 PM

kabibi said:

Thank you so much !!!

20/Sep/2011 18:08 PM

Mark said:

Helped so much. Thanks for posting.

07/Nov/2011 15:06 PM

siv said:

Nice solution

25/Nov/2011 14:32 PM

Ali said:

Great help, sorted issue for me as well. Thanks

01/Dec/2011 10:02 AM

Jalal khan said:

thank sir it is working fine

22/Dec/2011 08:37 AM

Hemant said:

Thaks lot Paul.

04/Feb/2012 09:33 AM

Straton said:

Thanks Paul, it working fine

05/Sep/2012 06:25 AM

Julian said:

Thanks Paul, very helpful

18/Sep/2012 15:18 PM

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!!

04/Oct/2012 17:05 PM

Mike said:

I am very happy to be part of your life! you're amazing. hehe

21/Feb/2013 07:28 AM

Add Comment

Name
Comment
 

Your comment has been received and will be shown once it passes moderation.