Search code examples
c#datatable

Making the first row in a DataTable the name of the columns


I´m trying to set the first row of a DataTable to be the column names. I´m using a GenericParsing library from Code Project. The problem is that the parser sets a default name for the columns.

Thanks.


Solution

  • This should do what you want:

    DataRow firstRow = table.NewRow();
    List<string> names = new List<string>();
    foreach (DataColumn column in table.Columns)
    {
        names.Add(column.ColumnName);
    }
    firstRow.ItemArray = names.ToArray();
    table.Rows.InsertAt(firstRow, 0);
    

    If the first row already exists and you want to "overwrite" this change the first line to:

    DataRow firstRow = table.Rows[0];
    

    And remove the last line.