Search code examples
c#visual-studio-2010t-sql

InvalidOperationException The connection was not closed. The connection's current state is open


Why does this code throw an Invalid Operation Exception?

private SqlCommand cmd; // initialized in the class constructor

public void End(string spSendEventNotificationEmail) {
  try {
    cmd.CommandText = spSendEventNotificationEmail;
    cmd.Parameters.Clear();
    cmd.Parameters.Add("@packetID", SqlDbType.Int).Value = _packetID;
    cmd.Parameters.Add("@statusID", SqlDbType.Int).Value = _statusID;
    cmd.Parameters.Add("@website", SqlDbType.NVarChar, 100).Value = Tools.NextStep;
    cmd.Connection.Open();
    cmd.ExecuteNonQuery();
  } finally {
    cmd.Connection.Close();
    cmd.Parameters.Clear();
    cmd.Dispose();
  }
  endCall = true;
}

InvalidOperationException


Solution

  • You're trying to open a connection which is already open, this results in exception.

    Solution 1 (recommended):

    Inspect your code, check all the parts where cmd.Connection connection is opened and ensure that it's always closed properly.

    Solution 2 (quick'n'dirty fix):

    before line

    cmd.Connection.Open();
    

    add the following check/cleanup code:

    if (cmd.Connection.State == ConnectionState.Open)
    {
        cmd.Connection.Close();
    }