It gives the error connection was not closed. Connection's current state is open. Please help out with the code.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\vicky\Desktop\Gym management system\Fitness_club\vicky.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
try
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * FROM [plan] where plantype='" + comboBox1.Text + "'", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string amount = dr.GetString(1);
textBox5.Text = amount;
}
con.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
You should be using
using
blocks to help with managing your objects.Also note the use of parameterized queries to avoid SQL injection attacks. Since you are probably only expecting one value to be returned, you should specify the name of the column in the query and use
ExecuteScalar
instead of the reader and thewhile
loop. The other alternative is to useCommandBehavior.SingleRow
as the parameter to the command, which tells the command to just return a single row result.You also have a cross-threading problem here, and you can solve it by using some invoking.
Another thing to note, is to give your controls meaningful names. Its a lot easier to debug or understand a control named
cbx_PlanType
thancombobox1
, ortbx_PlanAmount
rather thantextbox5
.