How to add rows to DataTable?

B

Brett Romero

I keep getting this error with the following code:
This row already belongs to another table

DataSet ds = new DataSet();
DataTable dtPersonID = new DataTable();
dtPersonID.Columns.Add("PersonID");
foreach (DataRow dr in dt.Rows)
{
dtPersonID.Rows.Add(dr);
}

Why does it matter if two tables have the same row? This is my first
pass through the app so dtPersonID does not have any rows. I'm
transferring the PersonID column from the dt table into dtPersonID.

Thanks,
Brett
 
N

Nicholas Paldino [.NET/C# MVP]

Brett,

It matters because the row has a Table property which it exposes that
indicates which table it is a part of.

You should be able to pass the row dr to the ImportRow method on the dt
DataTable to import the row (it really copies the row from one table to
another).

Hope this helps.
 
B

Brett Romero

Perfect! I just switched the .Add() for the .ImportRow().

How does ImportRow get around the above issue? In other words, what is
the difference between the two methods?

Thanks,
Bret
 
N

Nicholas Paldino [.NET/C# MVP]

Bret,

Basically, it calls AddNew on the Rows collection of the new table,
passing the values of the original row to the that method.
 
B

Brett Romero

I'd like to write the rows out to XML in a format similar to:
<ROOT><Person PersonId="119323" /><Person PersonId="119324" /></ROOT>

but ds.WriteXML() only gives
<PersonIDSet />

Here's the code used to get the dataset XML

System.IO.StringWriter sw = new System.IO.StringWriter();
XmlTextWriter xmltw = new XmlTextWriter(sw);

ds.WriteXml(xmltw, XmlWriteMode.IgnoreSchema);
string xml = sw.ToString();
Debug.WriteLine(xml);

I wanted to make sure the table rows have values. I'd tried this

for (int i = 0; i <dtPersonID.Rows.Count; i++)
Debug.WriteLine(dtPersonID.Rows.ItemArray);

but only get
System.Object[]

However, in the Command Window, I type dtPersonID.Rows[0].ItemArray and
get
{Length=1}
[0]: "57843"

Any ideas?

Thanks,
Brett
 
B

Brett Romero

I found the problem. That particular DataTable needed to be added to
the DataSet. It is writing now in this format:

<?xml version="1.0" standalone="yes"?>
<PersonIDSet>
<dtPersonID>
<PersonID>57843</PersonID>
</dtPersonID>
<dtPersonID>
<PersonID>58750</PersonID>
</dtPersonID>
</PersonIDSet>

How can I get it to write in this format:
<ROOT>
<PersonID>57843</PersonID>
<PersonID>58750</PersonID>
</ROOT>

Thanks,
Brett
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top