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

后端 未结 8 552
孤街浪徒
孤街浪徒 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....

    0 讨论(0)
  • 2020-11-30 06:44

    Or you can try to access the columns directly by name:

    while(dr.Read())
    {
        string col1 = (string)dr["Value1"];
        string col2 = (string)dr["Value2"];
        string col3 = (string)dr["Value3"];
    }
    
    0 讨论(0)
  • 2020-11-30 06:44

    Suppose your DataTable has the following columns try this code:

    DataTable dt =new DataTable();
    txtTGrossWt.Text = dt.Compute("sum(fldGrossWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldGrossWeight)", "").ToString();
    txtTOtherWt.Text = dt.Compute("sum(fldOtherWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldOtherWeight)", "").ToString();
    txtTNetWt.Text = dt.Compute("sum(fldNetWeight)", "").ToString() == "" ? "0" : dt.Compute("sum(fldNetWeight)", "").ToString();
    txtFinalValue.Text = dt.Compute("sum(fldValue)", "").ToString() == "" ? "0" : dt.Compute("sum(fldValue)", "").ToString();
    
    0 讨论(0)
  • 2020-11-30 06:53

    Actually the Read method iterating over records in a result set. In your case - over table rows. So you still can use it.

    0 讨论(0)
  • 2020-11-30 07:00
    while (dr.Read())
    {
        for (int i = 0; i < dr.FieldCount; i++)
        {
            subjob.Items.Add(dr[i]);
        }
    }
    

    to read rows in one colunmn

    0 讨论(0)
  • 2020-11-30 07:04

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

    IDataReader.Read() advances the reader to the next row in the resultset.

    while(reader.Read()){
        /* do whatever you'd like to do for each row. */
    }
    

    So, for each iteration of your loop, you'd do another loop, 0 to reader.FieldCount, and call reader.GetValue(i) for each field.

    The bigger question is what kind of structure do you want to use to hold that data?

    0 讨论(0)
提交回复
热议问题