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