c# - Connection was not closed. Connection's current state is open -
it gives error connection not closed. connection's current state open. please out 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 * [plan] 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 using using
blocks managing objects.
private void combobox1_selectedindexchanged(object sender, eventargs e) { string connstr = @"data source=.\sqlexpress;attachdbfilename=c:\users\vicky\desktop\gym management system\fitness_club\vicky.mdf;integrated security=true;connect timeout=30;user instance=true"; string cmdtext = "select * [plan] plantype=@plantype"; using (sqlconnection con = new sqlconnection(connstr)) using (sqlcommand cmd = con.createcommand()) { con.open(); cmd.commandtext = cmdtext; cmd.parameters.addwithvalue("@plantype", combobox1.text); var reader = cmd.executereader(commandbehavior.singlerow); if (reader.read()) { string amount = reader.getstring(1); textbox5.text = amount; } } }
also note use of parameterized queries avoid sql injection attacks. since expecting 1 value returned, should specify name of column in query , use executescalar
instead of reader , while
loop. other alternative use commandbehavior.singlerow
parameter command, tells command return single row result.
you have cross-threading problem here, , can solve using invoking.
string amount = string.empty; if (reader.read()) { amount = reader.getstring(1); } if (this.invokerequired) this.invoke((methodinvoker) delegate { textbox5.text = amount; }); else textbox5.text = amount;
another thing note, give controls meaningful names. lot easier debug or understand control named cbx_plantype
combobox1
, or tbx_planamount
rather textbox5
.
Comments
Post a Comment