Reputation: 3995
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;
}
Upvotes: 1
Views: 27047
Reputation: 473
You can not duplicate Column names by using Data Table
.Consider this and find another solution .
If you try to duplicate Column name then it will show an error like that you mentioned.
A column named 'Pressure' already belongs to this Data Table .
In here you try to duplicate Column name 'Pressure' that's why that error comes.
Upvotes: 0
Reputation: 343
Maybe you can make use of the DataColumn.Caption property to store the column display name:
https://msdn.microsoft.com/en-us/library/system.data.datacolumn.caption(v=vs.110).aspx
Upvotes: 2
Reputation: 85
for (int i = 0; i < dt_key.Rows.Count; i++)
{
if(dt_data.Columns.Contains(dt_key.Rows[i][0].ToString()))
dt_data.Columns[i].ColumnName = dt_key.Rows[i][0].ToString() + " " ;
else
dt_data.Columns[i].ColumnName = dt_key.Rows[i][0].ToString();
}
However adding a same column name is a bad practise,still you could achieve that by adding a space at the end of column name to make it unique.
Upvotes: 5
Reputation: 18105
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.
Upvotes: 6