连接没有关闭

The connection was not closed

这让我很头疼。我已经尝试 trycatchfinally 和其他东西,但这个错误不断出现。请有人帮忙。 我的 C# 代码:

 void show()
    {
       string str = "SELECT PID, Pname, Gender, ContactNum, Category, Department, Ward, AdmitDate, DischargeDate, NumOfDays, CostOfTest, NumOfDocsVisited, DocFee, BedCost, TotalCost, GrandTotal FROM Patient";
        cmd = new SqlCommand(str, con);
            con.Open();
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            GridView1.DataBind();
                con.Close();
    }

错误是:

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.

来源错误:

Line 50:            string str = "SELECT PID, Pname, Gender, ContactNum, Category, Department, Ward, AdmitDate, DischargeDate, NumOfDays, CostOfTest, NumOfDocsVisited, DocFee, BedCost, TotalCost, GrandTotal FROM Patient";
Line 51:             cmd = new SqlCommand(str, con);
Line 52:                 con.Open();
Line 53:                 SqlDataAdapter adp = new SqlDataAdapter(cmd);
Line 54:                 DataTable dt = new DataTable();

堆栈跟踪:

[InvalidOperationException: The connection was not closed. The connection's current state is open.]
System.Data.ProviderBase.DbConnectionInternal.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +14
System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +94
System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +110
System.Data.SqlClient.SqlConnection.Open() +96
SMC.Billing.show() in e:\VS2013 projects\SMC\SMC\Billing.aspx.cs:52
SMC.Billing.Button3_Click(Object sender, EventArgs e) in e:\VS2013 projects\SMC\SMC\Billing.aspx.cs:97
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628722
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

将您的连接包装在 using 块中。这保证它总是被关闭。

using (var connection = new SqlConnection(connectionString))
{
  connection.Open();
  //Do stuff with the connection
}

在我看来,它似乎在试图告诉您您正在尝试打开一个已经打开的连接。

你可以试试(第 52 行)

if (con.State == ConnectionState.Closed) con.Open;