Using c# how do I print all columns in a datareader.
string ColumnValue; if (dr["ColumnName"] != null) ColumnValue = dr["ColumnName"].
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.
Answers. It IS possible to handle multiple result sets with a reader. string sqlText = "Select this, that from here; select somethingelse from there"; ...
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;
}
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);
}
for (int j = 0; j < x.VisibleFieldCount; j++)
Console.WriteLine(x.GetName(j));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With