How do I loop through rows with a data reader in C#?
That's the way the DataReader
works, it's designed to read the database rows one at a time.
while(reader.Read()) { var value1 = reader.GetValue(0); // On first iteration will be hello var value2 = reader.GetValue(1); // On first iteration will be hello2 var value3 = reader.GetValue(2); // On first iteration will be hello3}
int count = reader.FieldCount;while(reader.Read()) { for(int i = 0 ; i < count ; i++) { Console.WriteLine(reader.GetValue(i)); }}
Note; if you have multiple grids, then:
do { int count = reader.FieldCount; while(reader.Read()) { for(int i = 0 ; i < count ; i++) { Console.WriteLine(reader.GetValue(i)); } }} while (reader.NextResult())