Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store connection string in WinForms application?

Tags:

c#

winforms

I have an application that consists of two forms. One form displays data returned from the database in fields and the other form opens a windows that allows the user to select which database to get the data from.

Currently, the application doesn't store the user's choice of database. I want to store what the currently selected connection string is each time the user selects the database they want to use in form2.

What is the best way to do this? If I made an instance of an object of a static class to store this information, would that persist the data for use on each form?

like image 555
Theomax Avatar asked Apr 02 '12 08:04

Theomax


1 Answers

You should have an app.config configuration file, and in there, define a <connectionStrings> section:

<configuration>
   <connectionStrings>
       <add name="YourNameHere" 
            connectionString="server=.;database=AdventureWorks;Integrated Security=SSPI"/>
   </connectionStrings>
</configuration>

You then add a reference to System.Configuration to your project, and then you can easily retrieve those connection strings:

string connStr = ConfigurationManager.ConnectionStrings["YourNameHere"].ConnectionString;

using(SqlConnection connection = new SqlConnection(connStr))
{
   // do something here....
}
like image 71
marc_s Avatar answered Oct 03 '22 22:10

marc_s