c# - Why I cannot use the using statement with my static method? -


this question has answer here:

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

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -