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

Slacker616 picture Slacker616 · Dec 3, 2011 · Viewed 171.8k times · Source

I know I can use while(dr.Read()){...} but that loops every field on my table, I want to retrieve all the values from the first row, and then second... and so on.

Let's say I have a table like this:

ID--------------Value1--------------Value2------------------Value3
1               hello               hello2                  hello3
2               hi1                  hi2                      hi3

first I want to get, hello, hello2 and hello3 and then go to the second row and get all the values.

Is there a way to achieve this? I hope somebody understand what I mean.

I am so sorry, this is solved now. I just wasn't coding right...

And yeah the SqlDataReader.Read() method does what it is supposed to do, again the mistake was mine.

Answer

Rich O'Kelly picture Rich O'Kelly · Dec 3, 2011

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
}