Can you get the column names from a SqlDataReader?

Blankman picture Blankman · Mar 25, 2009 · Viewed 237.8k times · Source

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

Answer

Rob Stevenson-Leggett picture Rob Stevenson-Leggett · Mar 25, 2009
var reader = cmd.ExecuteReader();

var columns = new List<string>();

for(int i=0;i<reader.FieldCount;i++)
{
   columns.Add(reader.GetName(i));
}

or

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