Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 333
Slacker616 Avatar asked Dec 03 '11 20:12

Slacker616


People also ask

Which function of DataReader is used to get the data from it?

ExecuteReader to retrieve rows from a data source. The DataReader provides an unbuffered stream of data that allows procedural logic to efficiently process results from a data source sequentially. The DataReader is a good choice when you're retrieving large amounts of data because the data is not cached in memory.

What does SqlDataReader return?

As explained earlier, the SqlDataReader returns data via a sequential stream. To read this data, you must pull data from a table row-by-row Once a row has been read, the previous row is no longer available.


2 Answers

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 } 
like image 102
Rich O'Kelly Avatar answered Oct 06 '22 10:10

Rich O'Kelly


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()) 
like image 29
Marc Gravell Avatar answered Oct 06 '22 09:10

Marc Gravell