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?