Force a SqlDataReader result

0

I have the following method:

        public ClassCardapio MontaCardapioEdit(string periodo, int tipo)
    {
        ClassCardapio cardapio = new ClassCardapio(_stringconexao);

        _conexao.Open();

        var sql = $"SELECT " +
                    "C.DESC_TIPO  as 'COMPOSIÇÃO'" +
                    ",B.SEGUNDA " +
                    ",B.TERCA " +
                    ",B.QUARTA " +
                    ",B.QUINTA " +
                    ",B.SEXTA " +
                    "FROM CARDAPIO A " +
                    "JOIN CARDAPIO_ITEM B ON A.ID = B.ID_CARDAPIO " +
                    "JOIN CARDAPIO_TIPO C ON B.TIPO = C.ID " +
                    "WHERE A.ID = '" + periodo + "' " +
                    "AND B.TIPO = '" + tipo + "' " +
                    "ORDER BY B.ID asc ";
        var cmd = new SqlCommand(sql, _conexao);
        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {

            cardapio.segunda = dr["SEGUNDA"].ToString();
            cardapio.terca = dr["TERCA"].ToString();
            cardapio.quarta = dr["QUARTA"].ToString();
            cardapio.quinta = dr["QUINTA"].ToString();
            cardapio.sexta = dr["SEXTA"].ToString();

        }

        _conexao.Close();

        return cardapio;
    }

The result of it:

I'm trying to create a textbox in a textbox, but I can not figure out how to do this. By default it is always displaying the last line of the 3.

    
asked by anonymous 04.08.2017 / 14:17

1 answer

1

The While statement executes the task, until the condition is false .

If your dr.Read() case causes the read line of your DataTable to be changed at each loop, so it will run until no lines exist.

Since 3 lines of the query are returned, the loop is executed 3 times, thus returning the value of the last line.

I do not guarantee it's the best alternative, but putting break at the end of the while will ensure that it only runs once.

OR, we can remove the While statement, which will make the system read only the first line.

  while (dr.Read())
    {

        cardapio.segunda = dr["SEGUNDA"].ToString();
        cardapio.terca = dr["TERCA"].ToString();
        cardapio.quarta = dr["QUARTA"].ToString();
        cardapio.quinta = dr["QUINTA"].ToString();
        cardapio.sexta = dr["SEXTA"].ToString();

        break;
    }

or

        dr.Read();

        cardapio.segunda = dr["SEGUNDA"].ToString();
        cardapio.terca = dr["TERCA"].ToString();
        cardapio.quarta = dr["QUARTA"].ToString();
        cardapio.quinta = dr["QUINTA"].ToString();
        cardapio.sexta = dr["SEXTA"].ToString();

To learn more about While

    
04.08.2017 / 14:28