Reputation: 23
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
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