c# - Apply same sql connection string to whole winform? -


i apply connection string whole winform. if in case - apply whole win form, cannot use textbox enter details:

public partial class form1 : form {     sqlconnection myconnection = new sqlconnection("user id=username;" +     "password=userpass;" +     "server=.;" +     "trusted_connection=yes;" +     "database=dbname; " +     "multipleactiveresultsets=true;" +     "connection timeout=30");      public form1()     {         initializecomponent();     } 

and if use textbox need enter connection string each method.

is there anyway around it?

another approach can take create sqlconnection when needed , store in private variable if want save reference.

so when need connection have:

if( myconnection == null ) {     string connectionstring = string.format( "user id={0}, password={1}", useridtextbox.text, passwordtextbox.text );   myconnection = new sqlconnection( connectionstring ); } 

you extend "string.format" include other connection properties.

if require "myconnection" in multiple places place above code method named "getconnection", have return sqlconnection instance using contents of textboxes , call method each time connection required.

edit:

personally have method builds connection string, described above, , create new sqlconnection instance whenever needed. attempt open new connection each time, make use of connection pooling built ado.net library.

using( sqlconnection connection = new sqlconnection( this.getconnectionstring() ) ) {     //  open connection     //  access database     //  close connection <- manual closing may not needed might done in dispose ...check msdn clarification. } 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -