0

Boa tarde, estava a realizar um código para fazer uma query a minha base de dados quando me apareceu estes erro: Error 1 The type or namespace name 'DataReader' could not be found (are you missing a using directive or an assembly reference?)

Sei que é algo simples mas se me pudessem dar uma ajuda ficava bastante grato. Aqui esta o código:

   {
        string connectionString = "Data Source=localhost; Initial Catalog=DB_SACC; User id=sa Password=1234;";
        decimal? average;
        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    string textt = "SELECT AVG (Total_Divida) AS 'AVG_DIVIDA' FROM t_pagamentos";
                    cmd.CommandText = textt;
                    connection.Open();
                    cmd.Connection = connection;
                    cmd.CommandType = CommandType.Text;

                    using (DataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            average = decimal.parse(reader["AVG_DIVIDA"].ToString());
                            break;

                        }
                    }
                }
            }


            TextBox3.Text = average.HasValue ? average.ToString() : "Unknown error occurred";

        }
        catch (Exception ex)
        {
            MessageBox.Show("Unable to retrieve the average, reason: " + ex.Message);


        }
5
  • 1
    Experimente substituir: DataReader reader = cmd.ExecuteReader() por: var reader = cmd.ExecuteReader().
    – Aline
    7/04/2017 às 16:56
  • resultou , mas agora esta a dar o seguinte erro : Error 1 'decimal' does not contain a definition for 'parse'. 7/04/2017 às 16:58
  • quer dizer este erro:Error 1 Use of unassigned local variable 'average' 7/04/2017 às 17:03
  • Basta declarar a variável: var average = Convert.ToDecimal(reader["AVG_DIVIDA"].ToString()); 7/04/2017 às 17:07
  • obrigado a todos este foi o erro que se deu despois de ter seguido o conselho de senhor Marcell : Error 1 A local variable named 'average' cannot be declared in this scope because it would give a different meaning to 'average', which is already used in a 'parent or current' scope to denote something else 7/04/2017 às 17:11

2 Respostas 2

1

O método ExecuteReader() retorna um SqlDataReader:

using (SqlDataReader reader = cmd.ExecuteReader())
{

}
0
0

Experimente substituir o tipo do reader para var no using e verificar se o valor que está chegando não é null:

{
    string connectionString = "Data Source=localhost; Initial Catalog=DB_SACC; User id=sa Password=1234;";
    decimal? average;
    try
    {
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                string textt = "SELECT AVG (Total_Divida) AS 'AVG_DIVIDA' FROM t_pagamentos";
                cmd.CommandText = textt;
                connection.Open();
                cmd.Connection = connection;
                cmd.CommandType = CommandType.Text;

                using (var reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        average = Convert.IsDBNull(reader["AVG_DIVIDA"]) ? 0 : Convert.ToDecimal(reader["AVG_DIVIDA"].toString());
                        break;

                    }
                }
            }
        }

        TextBox3.Text = average.HasValue ? average.ToString() : "Unknown error occurred";
    }
    catch (Exception ex)
    {
        MessageBox.Show("Unable to retrieve the average, reason: " + ex.Message);
    }
}
8
  • ja experimentei e esta a surguir o seguinte erro :Error 1 Use of unassigned local variable 'average ' 7/04/2017 às 17:05
  • decimal? average; remove o nullable. Põe: decimal average = 0;
    – Aline
    7/04/2017 às 17:07
  • Basta declarar a variável: var average = Convert.IsDBNull(reader["AVG_DIVIDA"]) ? 0 : Convert.ToDecimal(reader["AVG_DIVIDA"].toString()); 7/04/2017 às 17:07
  • obrigado a todos este foi o erro que se deu despois de ter seguido o conselho de senhor Marcell : Error 1 A local variable named 'average' cannot be declared in this scope because it would give a different meaning to 'average', which is already used in a 'parent or current' scope to denote something else 7/04/2017 às 17:23
  • @DiogoGomes É só você ler o texto que vai entender qual é o problema.
    – Jéf Bueno
    7/04/2017 às 17:31

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .