3

I'm filling a DataTable with SQL Server query results like so:

System.Data.DataTable dataTableSQL = new System.Data.DataTable();

// write the sqlCode to dataTableSQL via adapter
using (SqlConnection conn = new SqlConnection(@"Data Source=myServerName;Initial Catalog=myDB;Integrated Security = SSPI"))
{
    SqlDataAdapter adapter = new SqlDataAdapter();
    adapter.SelectCommand = new SqlCommand(SQLCode, conn);

    conn.Open();
    adapter.Fill(dataTableSQL);
    conn.Close();
}

This method seams to be omitting the column names from the dataTable. When I run the below code, I just get the first row of the query results:

foreach (DataColumn column in dataTableSQL.Columns)
{
    Console.WriteLine(dataTableSQL.Rows[0][column.ColumnName].ToString());
}

Here is a helpful reference, but unfortunately my tables are 30 + columns long, and my column names are dynamic, so it does me no good. DataTable DataColumn ColumnName not displaying

Is there an easy way to add dynamic column names to a dataTable so I can use them in reporting?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Jar
  • 1,766
  • 1
  • 21
  • 27
  • 1
    The column names are not in row zero. They are in an enumeration dataTableSQL.Columns property. Should be : Console.WriteLine(column.ColumnName); – jdweng Feb 24 '18 at 06:50
  • @jdweng perfect man thank you – Jar Feb 24 '18 at 15:06

0 Answers0