Can you get the column names from a SqlDataReader? – Dev

The best answers to the question “Can you get the column names from a SqlDataReader?” in the category Dev.


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


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.


var reader = cmd.ExecuteReader();

var columns = new List<string>();

for(int i=0;i<reader.FieldCount;i++)


var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();


Already mentioned. Just a LINQ answer:

var columns = reader.GetSchemaTable().Rows
                                     .Select(r => (string)r["ColumnName"])


var columns = Enumerable.Range(0, reader.FieldCount)

The second one is cleaner and much faster. Even if you cache GetSchemaTable in the first approach, the querying is going to be very slow.


You can get the column names from a DataReader.

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