Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

asp.net - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...