c# - Why I cannot use the using statement with my static method? -
this question has answer here:
- returning sqldatareader 5 answers
if use in class works properly, when call default.cs:
public class mymethodssql { public static sqldatareader metodocommand() { string cs = configurationmanager.connectionstrings["dbcs"].connectionstring; sqlconnection con = new sqlconnection(cs); sqlcommand cmd = new sqlcommand(); cmd.commandtext = "select * employees"; con.open(); cmd.connection = con; sqldatareader sdr = cmd.executereader(); return sdr; } } protected void button1_click(object sender, eventargs e) { gridview1.datasource = mymethodssql.metodocommand(); gridview1.databind(); }
but when use using statement error: says there no open connections
public class mymethodssql { public static sqldatareader metodocommand() { string cs = configurationmanager.connectionstrings["dbcs"].connectionstring; using (sqlconnection con = new sqlconnection(cs)) { sqlcommand cmd = new sqlcommand(); cmd.commandtext = "select * employees"; con.open(); cmd.connection = con; sqldatareader sdr = cmd.executereader(); return sdr; } } }
the sqlconnection close/dispose before returning datareader, , datareader needs open connection.
Comments
Post a Comment