PandaPlay123
PandaPlay123

Reputation: 23

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

I have a problem with my connection, I closed all connections before I created a new connection (Payment()), but it says that there is an open connection. I'm still new to C# so I really need your help...

Here is my code that has the problem:

public void Payment()
{
    // start session
    if (Session["User_Email"] != null)
    {
        string GUsername = Session["User_Email"].ToString();
        string ORnum = Session["OR"].ToString();
        int num =Convert.ToInt32(ORnum);

        conn.Open();    // this where error occurs

        query = "SELECT * FROM CartForDelivery where User_Email = '" + GUsername + "' and OR = '" + num + "';";

        SqlCommand cmd = new SqlCommand(query, conn);
        SqlDataReader dreader = cmd.ExecuteReader();

        while (dreader.Read())
        {
            lblpayment.Text = dreader.GetInt32(6).ToString();
        }

        dreader.Close();
        conn.Close();
    }    // end session
}

Error says:

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

This occurs on the line conn.Open();

Thanks again in advance! :)

Upvotes: 0

Views: 150

Answers (1)

usha
usha

Reputation: 77

     Please always use with in using () command as 
     //conn.Open();
     using(SqlConnection conn = new SqlConnection(connectionstring)){
        conn.Open();
     using(SqlCommand cmd = new SqlCommand(query, conn)){
            SqlDataReader dreader = cmd.ExecuteReader();

            while (dreader.Read())
            {
                lblpayment.Text = dreader.GetInt32(6).ToString();
           }
   }
 }

  It will automatically closes the object

Upvotes: 1

Related Questions