Using c# how do I print all columns in a datareader.
Asked
Active
Viewed 2.0k times
22
-
This may help http://stackoverflow.com/questions/2728170/system-data-common-dbdatareader/2728203#2728203 – Daniel Renshaw Apr 29 '10 at 15:48
3 Answers
32
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
- 167,292
- 40
- 290
- 283
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
- 242,243
- 40
- 408
- 536
-
1I love extension methods,i feel like injecting into and exposing that behaviour.. :) – Srinivas Reddy Thatiparthy Apr 29 '10 at 16:19
3
for (int j = 0; j < x.VisibleFieldCount; j++)
Console.WriteLine(x.GetName(j));

Tejs
- 40,736
- 10
- 68
- 86