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

后端 未结 8 553
孤街浪徒
孤街浪徒 2020-11-30 06:29

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 o

相关标签:
8条回答
  • 2020-11-30 07:06
    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())
    
    0 讨论(0)
  • 2020-11-30 07:07

    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
    }
    
    0 讨论(0)
提交回复
热议问题