关闭函数内的.netslclient数据提供程序

时间:2013-08-23 20:22:35

标签: c# asp.net

我有一个Listview绑定到一个名为GetAmountStyles()的函数。触发此函数时,它会创建44个SQL连接。无论我在哪里尝试关闭SQL连接,它都不会关闭。我在哪里以及如何关闭这些连接?

 protected string GetAmountStyle()
{
    //Makes SQl connection 
    SqlConnection testDBconn = new SqlConnection(ConfigurationManager.ConnectionStrings["testDBconn"].ConnectionString);
    //SqlCommand cmd = new SqlCommand();
   testDBconn.Open();

    System.Data.SqlClient.SqlCommand CurrAllsessions = new System.Data.SqlClient.SqlCommand("Select UserName from TenHrsLogins union Select UserName from permlogins ", testDBconn);
    SqlDataReader dr = CurrAllsessions.ExecuteReader();
    string Login = Convert.ToString(Eval("Login"));




    while (dr.Read())
    {
        //if (Login.Contains(dr.GetValue(0).ToString()) == true)
        if (Login.Contains(dr.GetValue(0).ToString()) == true)
        {

            dr.Dispose();
            return "background-color: #FFC6C6;";



        }
        else
        {



        }


    }
    dr.Dispose();
    testDBconn.Close();
    return "testDBconn.Close();";
}

1 个答案:

答案 0 :(得分:1)

你要回来了

return "background-color: #FFC6C6;";

关闭连接之前。根据经验使用,无需明确处置或关闭。像这样:

using(var testDBconn = new SqlConnection(...)) {
   testDBconn.Open();
   // do whatever you like with connection, it will close automatically
   using(var dr = CurrAllsessions.ExecuteReader()) {
     // do whatever you like with data reader
   }
}