How do I loop through rows with a data reader in C#? How do I loop through rows with a data reader in C#? asp.net asp.net

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())


Or you can try to access the columns directly by name:

while(dr.Read()){    string col1 = (string)dr["Value1"];    string col2 = (string)dr["Value2"];    string col3 = (string)dr["Value3"];}