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

0

I need to access a database where I put the data myself, the insert part is working, but now I need to "get" the data again when I click the button, so it does not matter what way I do it you always get this error message:

  

System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.'

My code is in this 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();
}

If you want to see the whole code HERE

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

    
asked by anonymous 22.01.2017 / 17:30

2 answers

1

As the error message itself says, the Connection property has not been initialized.

Any instance of SqlCommand need to have the connection defined.

This can be done at builder

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

or setting "the value of the property

sqlCommand.Connection = connection;

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

Ex:

cmd = new SqlCommand("SELECT * from Logins WHERE Condicao", connection);
    
23.01.2017 / 12:44
0

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

cmd.Connection = con;

I had forgotten to mention which connection I would be looking for.

Now my code looks 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();
}
    
22.01.2017 / 17:38