Reputation:
I am getting the following error message:
System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is Closed.
And here is my code:
public IDataReader ExecuteReader()
{
IDataReader reader = null;
try
{
this.Open();
reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch (Exception ex)
{
if (handleErrors)
strLastError = ex.Message;
else
throw;
}
catch
{
throw;
}
return reader;
}
Does anyone know how I can resolve this?
Upvotes: 0
Views: 506
Reputation: 9094
The Connection object that your SQLCommand is attached to has not been opened. You must open the connection before you can query.
Something like this:
private static void OpenSqlConnection(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
var cmd = connection.CreateCommand();
// Do your command access here.
}
}
Upvotes: 1