I have a .csv file that I am reading into C# via an OLEDBConnection. I am loading this into a DataSet. This step works fine. My data in the .csv file does not have any heading data/column headings. I want to add column headings to my DataSet in C# rather than directly into the .csv file. If I try to add column headings, then it just creates a new column on the end of the data, however I want to add the heading to the existing columns that already have data in it rather than create a new column.
1 Answer
Just access the column using index and the change the name
DataTable table = your datatable;
table.Columns[0].ColumnName = "Foo";
5 Comments
LeedsWalker
Thank you that now enables me to add a column heading. However adding the column headings means that I now lose my first row of data as the column headings are overwriting what was my first row. I obviously need to keep all data intact and just add the column headings before the first data row.
Sujith C Nair
Do you have something similar to this in your code "table.Columns.Add" Can you please share that part of the code. It is a common practice to read the first line and assign the values as column names. I think you are doing something similar
LeedsWalker
No, I've not used tables.Columns.Add as that appends a new column to the existing columns. I've used as you suggested table.Columns[0].ColumnName and this correctly labels the first column, but in doing so removes the first row of data. I will post the code in a new comment.
LeedsWalker
using (var conn = new OleDbConnection(connString)) { conn.Open(); var query = "SELECT * FROM [" + Path.GetFileName(fileName) + "]"; using (var adapter = new OleDbDataAdapter(query, conn)) { adapter.Fill(dt); } dt.Columns[0].ColumnName = "Column1"; dt.Columns[1].ColumnName = "Column2"; }
Sujith C Nair
Ok make sure you have HDR=No in your connection string.