How to add rows to DataTable?

  • Thread starter Thread starter Brett Romero
  • Start date Start date
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
 
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.
 
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
 
Bret,

Basically, it calls AddNew on the Rows collection of the new table,
passing the values of the original row to the that method.
 
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
 
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
 
Back
Top