21

Using c# how do I print all columns in a datareader.

Justin Niessner
  • 229,755
  • 35
  • 391
  • 521
svon
  • 315
  • 1
  • 6
  • 14

3 Answers3

31

This method will return an enumerable list of column names when passed a datareader:

static List<string> GetDataReaderColumnNames(IDataReader rdr)
{
    var columnNames = new List<string>();
    for (int i = 0; i < rdr.FieldCount; i++)
        columnNames.Add(rdr.GetName(i));
    return columnNames;
}
D'Arcy Rittich
  • 153,827
  • 35
  • 271
  • 277
14

To add some value to the answers, I included a possible extension method to return the column names for a given DataReader.

public static IEnumerable<string> GetColumnNames(this IDataReader reader)
{
    for(int i=0; i<reader.FieldCount; i++)
        yield return reader.GetName(i);
}
Justin Niessner
  • 229,755
  • 35
  • 391
  • 521
3
for (int j = 0; j < x.VisibleFieldCount; j++)
            Console.WriteLine(x.GetName(j));
Tejs
  • 38,896
  • 8
  • 64
  • 81