views:

1167

answers:

4

Hi,

After connecting to the database, can I get the name of the all the columns that where returned in my sqldatareader?

+4  A: 

there is a GetName function on the SqlDataReader which accepts the column index and returns the name of the column.

conversely, there is a GetOrdinal which takes in a column name and returns the column index.

Stephen Wrighton
A: 

You can get the column names from a DataReader... here is an article that gives an overview.

Here is the important part:

  for (int col = 0; col < SqlReader.FieldCount; col++)
  {
    Console.Write(SqlReader.GetName(col).ToString());         // Gets the column name
    Console.Write(SqlReader.GetFieldType(col).ToString());    // Gets the column type
    Console.Write(SqlReader.GetDataTypeName(col).ToString()); // Gets the column database type
  }
Steven Lyons
+1  A: 
var reader = cmd.ExecuteReader();

var columns = new List<string>();

for(int i=0;i<reader.FieldCount;i++)
{
   columns.Add(reader.GetName(i));
}
Rob Stevenson-Leggett
A: 

You sure can.

protected void GetColumNames_DataReader()
{
  System.Data.SqlClient.SqlConnection SqlCon = new System.Data.SqlClient.SqlConnection( "server=localhost;database=northwind;trusted_connection=true" );
  System.Data.SqlClient.SqlCommand SqlCmd = new System.Data.SqlClient.SqlCommand( "SELECT * FROM Products", SqlCon );

  SqlCon.Open();

  System.Data.SqlClient.SqlDataReader SqlReader = SqlCmd.ExecuteReader();
  System.Int32 _columncount = SqlReader.FieldCount;

  System.Web.HttpContext.Current.Response.Write( "SqlDataReader Columns" );
  System.Web.HttpContext.Current.Response.Write( " " );

  for ( System.Int32 iCol = 0; iCol 

This is originally from: http://www.dotnetjunkies.ddj.com/Article/B82A22D1-8437-4C7A-B6AA-C6C9BE9DB8A6.dcik

Jeremiah Peschka

related questions