Invalid operation exception

i have a question in invalid operation exception. it says that " ExecuteReader Connection is closed and must be open

SqlConnection conn = new SqlConnection("Server=localhost\\\\SqlExpress;" +
"Database=db;Integrated Security=True");
            SqlCommand comm = new SqlCommand("SELECT EmpID, Name FROM Employee", conn);
           
            SqlDataReader reader = comm.ExecuteReader();

ok,the problem solved

add this line before reader

comm.Connection.Open();

SqlConnection conn = new SqlConnection("Server=localhost\\\\SqlExpress;" +
"Database=db;Integrated Security=True");
            SqlCommand comm = new SqlCommand("SELECT EmpID, Name FROM Employee", conn);
            comm.Connection.Open();
            SqlDataReader reader = comm.ExecuteReader();

Make sure you close that connection and that reader. Best bet would be to wrap both in a using block:


using (var conn = new SqlConnection(cstring))
using (var cmd = conn.CreateCommand())
{
    cmd.CommandText="SELECT foo FROM bar";
    conn.Open();
    using (var r = cmd.ExecuteReader()){
        // do stuff
        r.Close();
    }
    conn.Close();
}

i like to add, if you would use the using you wont need to explicitly close the connection, .net would do that for you.

True, but I’d generally contend that it is better to have explicit intent rather than rely upon implicit behavior.