I am trying to run over all the fields of a row returned by ExecuteReader(), see here:
SqlCommand cmd = new SqlCommand(@"select * from People;", conn);
rdr = cmd.ExecuteReader();
while (rdr.Read())
{
foreach (Object i in rdr)
{
Console.WriteLine(i.ToString() + " ");
}
}
This outputs to the console:
System.Data.Common.DataRecordInternal
What should I put instead of object, as some of the fields are numerical (probably being internally cast to int) and some arevarchar (probably being internally cast to string). I did try string but that throws an error on the numerical fields. Likewise, using type var won’t compile.
Thanks.
When you iterate
foreach (object i in rdr)you are iterating the rows, not the columns. See the documentation for the data reader’sGetEnumerator()method. That’s why the ToString override is returningSystem.Data.Common.DataRecordInternal: you’re callingToString()on the whole data record, not just one of its values.To iterate the values of the reader’s current row, call the
GetValues()method instead; thisreturns an array of objects corresponding topopulates an array of objects with the values for the current row: