0

I would like to apply my connection string to the whole winform. If I do this in this case - it will apply to the whole win form, but then i cannot use textbox to 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 I will use with textbox I will need to enter the connection string to each method.

Is there anyway to get around it?

2 Answers 2

1

Another approach you can take is create the SqlConnection when it is needed and then store in a private variable if you want to save the reference.

So when you need the connection have:

if( myConnection == null )
{
    string connectionString = string.Format( "user id={0}, password={1}", userIdTextBox.Text, passwordTextBox.Text );
  myConnection = new SqlConnection( connectionString );
}

You will extend the "string.Format" to include the other connection properties.

If you require the "myConnection" in multiple places then place the above code into a method named "GetConnection", have it return an SqlConnection instance using the contents of the textboxes and call this method each time a connection is required.

EDIT:

Personally I would have a method that builds the connection string, like described above, and create a new SqlConnection instance whenever it is needed. This will attempt to open a new connection each time, but will make use of connection pooling built into the ADO.NET library.

using( SqlConnection connection = new SqlConnection( this.GetConnectionString() ) )
{
    //  Open Connection
    //  Access the database
    //  Close the connection <- Manual closing MAY not be needed as it might be done in Dispose ...check MSDN for clarification.
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can create a static class to store the connection string in there. It is not a good practice to create always the connection string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.