Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

datatable

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.

like image 531
cyberbrain Avatar asked Jan 03 '12 13:01

cyberbrain


People also ask

How do I get the first row of a DataTable?

use Datatable. rows(0) this will give you the first row in the datatable.

What is the first row of a table called?

A table header is a row at the top of a table used to label each column.


2 Answers

I think you need the following:

foreach (DataColumn column in table.Columns)
{
    string cName = table.Rows[0][column.ColumnName].ToString();
    if (!table.Columns.Contains(cName) && cName != "")
    {
         column.ColumnName = cName;
    }

}

table.Rows[0].Delete(); //If you don't need that row any more
like image 107
Alex Dn Avatar answered Oct 12 '22 23:10

Alex Dn


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.

like image 27
Shadow Wizard Hates Omicron Avatar answered Oct 13 '22 00:10

Shadow Wizard Hates Omicron