You are not Logged in
Would you like to Login or Register

Today is: Friday, 21 November, 2008
Check this months hot topics

"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

kick it on DotNetKicks.com del.icio.us digg Mister Wong YahooMyWeb Reddit Furl Spurl blogmarks
Paul Marshall Skype
Author : Paul Marshall
Published : Tuesday, 24 October, 2006

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

February 02, 2007 - 10:30 AM

reza said:

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

February 07, 2007 - 8:49 AM

sa_keles said:

thanks Paul it was very helpful for me :)

February 28, 2007 - 2:35 PM

sindia said:

thanks a lot

March 16, 2007 - 5:38 AM

Aki said:

Thanks ! worked perfectly!

March 22, 2007 - 5:10 PM

Alex said:

Thanks a lots Paul. It solved my problem. _

April 04, 2007 - 2:32 AM

Nasim said:

Hey it worked.. thanks..

April 05, 2007 - 11:17 AM

susanta said:

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

April 23, 2007 - 11:27 AM

Ajay said:

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

April 27, 2007 - 2:40 PM

Mandeep said:

Good Work!

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

Vinoth said:

Thanks buddy..great work..really helpful..:-)

May 16, 2007 - 5:28 PM

Vinoth said:

Thanks buddy..great work..really helpful..:-)

May 16, 2007 - 5:36 PM

Tom said:

Thanks, worked for me too!

June 19, 2007 - 5: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);

June 20, 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 :)

June 28, 2007 - 5:44 AM

Gopinath said:

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

July 18, 2007 - 1:08 PM

Pandex said:

Thanks was so hellful, great solution

July 20, 2007 - 6:45 PM

Matt Hunter said:

Thank you so much! I was getting pretty frustrated!

July 21, 2007 - 2:01 AM

Vinh said:

You're awesome!!!

August 13, 2007 - 10:20 PM

Vikram said:

Thanks a lot,

It solved my problem that was struked for a long time

Thanks again

August 16, 2007 - 4: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.

August 21, 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

October 04, 2007 - 5:42 AM

Levanter30 said:

Thanks! This is exactly what i needed

:-)

October 11, 2007 - 5:13 PM

dannyc said:

good work man, thanks!

October 26, 2007 - 2:50 PM

Ali said:

Thanks buddy!!

November 12, 2007 - 7:32 AM

Jules said:

So many "thanks", here's another

November 25, 2007 - 10: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.

December 04, 2007 - 4:41 PM

Naveen Kumar M said:

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

December 14, 2007 - 4:55 AM

SparkyRoosta said:

AWESOME! Thanks for that!

Gotta love GoogleMagic!

December 18, 2007 - 11:29 PM

Intellect India said:

Excellent..Tnx Paul!

January 18, 2008 - 4:25 AM

myro said:

thx!!!

January 28, 2008 - 1:50 PM

Arturomar said:

Just thanks, thanks, very much.

January 30, 2008 - 8:55 PM

lalitha said:

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

February 11, 2008 - 9:50 AM

itsme said:

Its working fine thanx.

February 15, 2008 - 6: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.

March 14, 2008 - 8:58 PM

Azarue said:

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

March 31, 2008 - 10:05 PM

nj said:

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

April 21, 2008 - 10:12 AM

Sid said:

Thanks, This is just the solution I was looking for

April 23, 2008 - 2:25 PM

Rania Nazmey said:

Really helpfull. i applied it in my code ;)

Thanks alot

April 24, 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();
                        }
May 13, 2008 - 7: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

May 13, 2008 - 10:28 AM

David said:

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

June 02, 2008 - 9: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";

June 03, 2008 - 10: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!

June 19, 2008 - 4:51 AM

Radhika said:

thanks a lot...

it worked!!!

June 19, 2008 - 8:29 AM

sreenup_mca2004@yahoo.co.in said:

Thanks Paul

June 30, 2008 - 1:03 PM

Janssen said:

Thanks my friend,

It solved my problem.

I was very frustrated for a long time

Thanks again from Costa Rica...

July 09, 2008 - 7:55 AM

.net fever said:

working like a charm !! Thanks a lot man

July 10, 2008 - 3:58 PM

kougar said:

Thanks for the easy answer bro.

August 27, 2008 - 8:08 PM

KK said:

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

September 04, 2008 - 1:29 AM

w said:

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

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

September 08, 2008 - 2:18 AM

Brian said:

Awesome job, Paul. You are my new hero. :-)

October 01, 2008 - 8:57 PM

Abel said:

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

Thanks,

October 08, 2008 - 6: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

October 15, 2008 - 2: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.

November 20, 2008 - 7:05 PM

Add Comment

Enter your comment below and it will be submitted for moderation.

Your Name

Add Tag

Please enter tags for this article, seperated by semi-colon ;

View Tag's by : # articles | # views