1

I have just completed my first project in WPF using C# and MS SQL 2008 express. I have used Visual Studio 2010. What I have right now is a class `conn.cs' that has a method that returns me the connection string as and when I require. Also I just noticed that I have an App.Config file that also has a connection string defined there (both strings refer to the same database).

My conn.cs

class conn
    {
        public string get_connection()
        {
            string conn_string = @"Data Source=.\sqlexpress;Initial Catalog=msp;Integrated Security=True;Pooling=False";
            return conn_string;
        }
    }

App.Config

<connectionStrings>
        <add name="msp.Properties.Settings.mspConnectionString" connectionString="Data Source=.\sqlexpress;Initial Catalog=msp;Integrated Security=True;Pooling=False" providerName="System.Data.SqlClient"/>
</connectionStrings>

I want to know two things now.

  1. How can I fetch the Connection String from the App.Config? I need to do this then, I will fetch the string in my conn.cs from there, and then, I will just change the connection string in the app.config as and when required.
  2. Also tell me, is it possible to set connection string at run time? I want the user to browse to the database (.mdf) file on First Run and then the connection string should get generated and saved in app.config. I can then easily pick it up from there and use.

Please provide suggestions.

1 Answer 1

1

You should be able to get access your connection string using this:

string connString = Properties.Settings.Default.mspConnectionString;

(when typing Properties.Settings.Default you should automatically see your choices in the Member List)

You can of course set the connection string at runtime; it is basically just another string. I would not recommend hard-coding the connection string; though.

You might want to give the SqlConnectionStringBuilder class a try; see this MSDN article for example. But actually I never used it so far except for a few experiments here and there although I literally only do database-driven software...

Sign up to request clarification or add additional context in comments.

3 Comments

I will give it a try and will post here soon.
Can I SET the ConnectionString in app.config at runtime? I guess the above code allows only getting.
Never tried that actually; as a ConnectionString is always an ApplicationSetting and not a UserSetting I do not think you can save it during runtime. But you could try creating a String UserSetting and use this for storing the connection string; these can be overwritten and saved.

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.