SamFisher83 SamFisher83 - 2 months ago 30
C# Question

duplicate datatable column names

I have a datable with column names I0,I1,I2 etc. However these aren't actual column names. I store the column names in another table.

I then have a loop to map the actual column names as follows:

for (int i = 0; i < dt_key.Rows.Count; i++)
{
dt_data.Columns[i].ColumnName = dt_key.Rows[i][0].ToString();
}


I get the following errors:


A column named 'Pressure' already belongs to this DataTable.


and


A column named 'Size' already belongs to this DataTable.


Ultimately I am trying to write this to a xml file:

dt_data.WriteXml(filename);


This works but I end up the column names I0..I22

There are similar questions to this, but they are trying to make datatables with duplicate columns names. I am just trying to print out a table with duplicate column names. What is a good method to do this?

Edit:

I can do the following:

for (int i = 0; i < dt_key.Rows.Count; i++)
{
dt_data.Columns[i].ColumnName = dt_key.Rows[i][0].ToString() + " " + dt_data.Columns[i].ColumnName;
}

Answer

I think the short answer to your question is that there is no way to have duplicate column names using a DataTable. What exactly are you using this XML for? There are lots of alternate ways to generate XML that give you a lot more fine grained control.

You could manually create your file using an XmlWriter object. This method creates an XmlWriter that writes to a file.