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

Hi all,

I am trying to execute two commands and i received this error that says that " The connection was not closed. The connection's current state is open".  

Here is what i have.
    try
                {
                    myConnection.Open();
                    if ((int)cmd1.ExecuteScalar() == 1)
                    {
                        //update function
                        Bind_Data();
                        cmd0.ExecuteNonQuery();
                        txtTexbox1.Text = "Record Updated";
                    }
                    else
                    {
                        cmd.ExecuteNonQuery();

                        txtTexbox1.Text = "Saved";

                    }
               

                }
                catch (Exception exc)
                {
                    txtTexbox1.Text = exc.Message;
                }
                finally
                {
                    myConnection.Close();

                }


ANy suggestion?
shpresaAsked:
Who is Participating?
 
Jacques Bourgeois (James Burger)PresidentCommented:
BindData probably contains code that calls Open on the same Connection object. If so, because the connection is already opened, you will get an error in BindData.

Make sure that it is opened in only one place, or close it after your ExecuteScalar.
0
 
Obadiah ChristopherCommented:
try
                {
                    if(myConnection.State == ConnectionState.Closed)
{
                    myConnection.Open();
}

Open in new window


finally
                {
                     if(myConnection.State == ConnectionState.Open || myConnection.State == ConnectionState.Broken)
                      myConnection.Close();

                }

Open in new window

0
 
anarki_jimbelCommented:
Just to add:


I believe the error happens because of the following line:

myConnection.Open();

Open in new window


Check if connection is already opened.
And it's up to you - you may close and open it again. Or use it as it is :).

One more thought. Looks like the connection was opened somewhere before your code is executed. Probably it had to be closed but wasn't. I'd find the place and close there...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.