Error: 'Executereader: Connection property has not been initialized. '

Asked

Viewed 3,407 times

0

I need to make an access to a database where I put the data myself, the insertion part is working, but now I need to "take" the data again when I click on the button, only it does not matter the way I always do give that error message:

System.Invalidoperationexception: 'Executereader: Connection property has not been initialized.'

My code is in that form:

public void RetornaUser(string Service)
{
    cmd = new SqlCommand("SELECT * from Logins WHERE Servico = @Service AND Estado = @Estado");
    cmd.Parameters.AddWithValue("@Servico", Service);
    cmd.Parameters.AddWithValue("@Estado", Estado);
    con.Open();

    SqlDataReader leitor = cmd.ExecuteReader();
    while (leitor.Read())
    {
        //passo os valores para o objeto cliente 
        //que será retornado 
        string Login = leitor["Login"].ToString();
        MessageBox.Show(Login);
    }

    //fecha conexão 
    con.Close();
}

In case you want to see all the code this HERE

In case I wanted to know how I do to remove the data and move to a variable so that my function returns to the other the account data so that it can use.

2 answers

1

As the error message itself says, the property Connection was not incialized.

Any and all instances of SqlCommand accurate have the connection set.

This can be done on its own builder

var sqlCommand = new SqlCommand("Select * From Logins", connection);

or "settando" the value of the property

sqlCommand.Connection = connection;

So, just adapt your code to have set up a connection on SqlCommand.

Ex.:

cmd = new SqlCommand("SELECT * from Logins WHERE Condicao", connection);

0

Good guys, I managed to find the error was missing a small line of code so I could perform the connection:

cmd.Connection = con;

I forgot to mention what connection I’d be looking for.

Now my code is like this:

public void RetornaUser(string Service)
{
    cmd = new SqlCommand("SELECT * from Logins WHERE Servico = @Service AND Estado = @Estado");
    cmd.Parameters.AddWithValue("@Service", Service);
    cmd.Parameters.AddWithValue("@Estado", Estado);
    con.Open();
    cmd.Connection = con;
    SqlDataReader leitor = cmd.ExecuteReader();
    while (leitor.Read())
    {
        //passo os valores para o objeto cliente 
        //que será retornado 
        string Login = leitor["Login"].ToString();
        string Senha = leitor["Senha"].ToString();
        MessageBox.Show("Login:"+Login+"\nSenha:"+Senha);
    }

    //fecha conexão 
    con.Close();
}
  • do not forget to mark your answer as the correct one

Browser other questions tagged

You are not signed in. Login or sign up in order to post.