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

后端 未结 8 592
孤街浪徒
孤街浪徒 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 06:43

    There is no way to get "the whole row" at once - you need to loop through the rows, and for each row, you need to read each column separately:

    using(SqlDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
            string value1 = rdr.GetString(0);
            string value2 = rdr.GetString(1);
            string value3 = rdr.GetString(2);
        }
    }
    

    What you do with those strings that you read for each row is entirely up to you - you could store them into a class that you've defined, or whatever....

提交回复
热议问题