Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print all columns in a datareader

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

like image 579
svon Avatar asked Apr 29 '10 15:04

svon


People also ask

How do I check if a DataReader has a column?

string ColumnValue; if (dr["ColumnName"] != null) ColumnValue = dr["ColumnName"].

How do I get data from ExecuteReader?

To retrieve data using a DataReader, create an instance of the Command object, and then create a DataReader by calling Command. ExecuteReader to retrieve rows from a data source.

Can DataReader have multiple tables?

Answers. It IS possible to handle multiple result sets with a reader. string sqlText = "Select this, that from here; select somethingelse from there"; ...


3 Answers

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;
}
like image 161
D'Arcy Rittich Avatar answered Oct 13 '22 12:10

D'Arcy Rittich


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);
}
like image 36
Justin Niessner Avatar answered Oct 13 '22 11:10

Justin Niessner


for (int j = 0; j < x.VisibleFieldCount; j++)
            Console.WriteLine(x.GetName(j));
like image 45
Tejs Avatar answered Oct 13 '22 12:10

Tejs