连接未关闭

时间:2015-05-08 18:17:03

标签: c# asp.net webforms

这是我的头脑。我已尝试trycatch finally和其他事情,但这个错误不断回来。请一些帮助。 我的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();
    }

错误是:

  

连接未关闭。连接的当前状态是打开的。   描述:执行期间发生未处理的异常   当前的网络请求。请查看堆栈跟踪了解更多信息   有关错误的信息以及它在代码中的起源   异常详细信息:System.InvalidOperationException:连接   没有关闭。连接的当前状态是打开的。

来源错误:

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

2 个答案:

答案 0 :(得分:2)

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

您可以尝试(第52行)

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

答案 1 :(得分:1)

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

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