Search code examples
c#code-behind

The connection was not closed. The connection's current state is Open


I'm getting this error. I've read posts that said to use a Using block, but I have one and I'm still getting the error.

My code-behind is:

    protected void btnEdit_OnClick(object sender, EventArgs e)
    {
        MdlCommentsExtender.Enabled = true;
        MdlCommentsExtender.Show();
        Button button = (Button)sender;
        string buttonId = button.ID;
        string[] tokens = buttonId.Split('-');
        ScriptManager.GetCurrent(this).SetFocus(this.txtCommentBox);

        //**************************/
         try
         {

             using (SqlConnection conn = new SqlConnection())
             {
                 conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnCST"].ToString();
                 conn.Open();
                 SqlCommand cmd2 = new SqlCommand();
                 cmd2.Connection = conn;
                 string CmdTxt = "Select CBL.ID, CBL.[Category], CBL.[Provision], CTL.MarkForReview, CTL.IssueType, CTL.Resolution, CTL.Feedback, CTL.TemplateID";
                 CmdTxt = CmdTxt + " from [tblCSTBenefitList] CBL";
                 CmdTxt = CmdTxt + " LEFT JOIN tblCSTTemplateList CTL";
                 CmdTxt = CmdTxt + " ON CBL.ID = CTL.BenefitID";
                 CmdTxt = CmdTxt + " where CBL.ID > '0'";
                 CmdTxt = CmdTxt + " ORDER BY CBL.[Category], CBL.[Provision] ASC";

                 cmd2.CommandText = CmdTxt;
                 SqlDataReader reader;
                 conn.Open();
                 reader = cmd2.ExecuteReader();
                 reader.Read();

                 lblBenCatX.Text = Convert.ToString(reader["Category"]);
                 lblBenProvX.Text = Convert.ToString(reader["Provision"]);
                 txtCommentBox.Text = Convert.ToString(reader["Feedback"]);
             }
         }
         catch (Exception ex) 
         { 
             Response.Write(ex.Message); 
         }

        /*******************************************/

        //txtCommentBox.Text = "First: " + tokens[0] + " and then " + tokens[1] + "";
    }

It's happening on the conn.Open(); line. Any ideas?


Solution

  • You are trying to open the connection twice, you have conn.Open() 2 times in your method, but you are newer closing the connection before trying to "re-open" it.

    Are you sure you want to open the connection twice? Try removing the second conn.Open(), that should actually work.