c# - Connection to database -


i trying create class can use within application connect database , run queries needed. found this post not quite working expect.

here class:

using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.data.sqlclient; //a class returns connection database namespace epacube_utility_tool {     public class epacube_db     {          public static sqlconnection getconnection()         {             string str = "user id=myusername;" +                "password=mypassword;server=myserver;" +                "database=mydatabase; " +                "connection timeout=30";              sqlconnection con = new sqlconnection(str);             con.open();             return con;         }                 } } 

and here how trying use it:

 private void button1_click(object sender, eventargs e)  {          var connection = epacube_db.getconnection();      connection.open();          sqldatareader rdr = null;      string commandtext = "select field1, field2 tablename";          sqlcommand cmd = new sqlcommand(commandtext, connection);          rdr = cmd.executereader();      while (rdr.read())      {          this.combobox1.items.add(rdr["field1"].tostring() +    ": " + rdr["field2"].tostring());      }      connection.close();  } 

when press button error

invalidoperationexception: connection not closed. connection's current state open.

what doing wrong? thanks, leslie

getconnection calls open you, you're calling again manually after called getconnection. call inside getconnection or outside, not both places.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -