1
votes

How do I stop ASP.NET, C# class functions throwing Connection not closed exception before the using statement instantiates the connection? This is happening when debugging in Visual Studio 2019 community.

1.Unchecking "Just my Code" in debug settings 2.Adding a "Finally {conn.Close()}" to nested using statement 3.Removing the try/catch from using statement 4.Checking all methods and functions called before the function throwing the error for malformed syntax or code

    /// <summary>
    /// Gets all colleges currently in db
    /// </summary>
    /// <returns>College object list</returns>
public List<College> getAllColleges()
{
    List<College> allColleges = new List<College>();
    using (SqlConnection conn = new SqlConnection(DbHelper.ConnectionString))
    { 
        using (SqlCommand cmd = new SqlCommand("getAllColleges", conn))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            conn.Open();
            try
            {
                SqlDataReader dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    //once the college code is known, get college specific information
                    College c = new College();
                    c = getCollegeByColCode(dr["col"].ToString());
                    allColleges.Add(c);
                }

            }
            catch (Exception e)
            { throw e; }

        }

    }

    //order list by college name
    allColleges.OrderBy(o => o.colFullName).ToList();
    return allColleges;
}

ERROR THROWN AFTER allColleges LIST IS BUILT BUT BEFORE USING STATEMENT

The connection was not closed. The connection's current state is open. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: The connection was not closed. The connection's current state is open.

Source Error:

Line 115: { Line 116:
Line 117: List colleges = new List(); Line 118: using (SqlConnection conn = new SqlConnection(DbHelper.ConnectionString)) Line 119: {

Source File: C:_dev\SNQProject\SNQLibrary\SNQLibrary\Classes\College.cs Line: 117

Stack Trace:

[InvalidOperationException: The connection was not closed. The connection's current state is open.] SNQLibrary.Classes.College.getAllColleges() in C:_dev\SNQProject\SNQLibrary\SNQLibrary\Classes\College.cs:117 Admin_SNQAdmin.buildCollegeSelect(String colCode) in c:_dev\SNQ\Admin\SNQAdmin.master.cs:191 Admin_Default.finalizeLogIn() in c:_dev\SNQ\Admin\Default.aspx.cs:135 Admin_Default.btnLogin_Click(Object sender, EventArgs e) in c:_dev\SNQ\Admin\Default.aspx.cs:98 System.Web.UI.WebControls.Button.OnClick(EventArgs e) +11758848 System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5028

1
Did you try to open the connection before creating the command ? (I mean as the first instruction inside the first using block, before creating the second using block).Enrico Massone
Another point of attention: what are you doing inside the function getCollegeByColCode ? Are you using the connection conn inside that function ?Enrico Massone
Thanks Enrico. I have tried moving the connection open command to the first using block and am getting the same error. Also getCollegeByColCode does use the same connection string, but not the same connection object. It's re instantiated for each call. Also the code breaks before that function is called.user3014776

1 Answers

0
votes

This error could tell you that the connection on an other place has not been closed.

Please try not opening a new connection or close all connections when execution finished.