Friday, April 15, 2011

Can you get the column names from a sqldatareader?

Hi,

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

From stackoverflow
  • 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.

  • 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
      }
    
  • var reader = cmd.ExecuteReader();
    
    var columns = new List<string>();
    
    for(int i=0;i<reader.FieldCount;i++)
    {
       columns.Add(reader.GetName(i));
    }
    
  • 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

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.