C# .NET - Is there any way to declare single connection string in windowapp

Asked By mani on 01-Feb-12 02:39 AM
hi..Is there any way to declare connection string as globaly in window application like webconfig in webapplication..using c#.net
dipa ahuja replied to mani on 01-Feb-12 02:40 AM
Yes add app.config file and write there : <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
  <add key="name" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
  </appSettings>
</configuration>
 
 
string s = ConfigurationSettings.AppSettings["name"].ToString();
      
 
Reena Jain replied to mani on 01-Feb-12 02:47 AM
hi,

You can save connection string in Windows Application configuration (App.config) in windows form project

he following code shows how you can store connection strings in App.config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <connectionStrings>
  <add name="MyDBConnectionString" providerName="System.Data.SqlClient"
    connectionString="Data Source=localhost;Initial Catalog=MySQLServerDB; Integrated Security=true" />
   </connectionStrings>
</configuration>

Once you have saved your connection string in App.config file you can use System.Configuration.ConfigurationManager class to read this connection string in code.

ConnectionStringSettings  conSettings = ConfigurationManager.ConnectionStrings["MyDBConnectionString"];

ConnectionStringsSettings class provides properties to read connection string settings in your program as following code shows.
string name = conSettings.Name;
string providerName = conSettings.ProviderName;
string connectionString = conSettings.ConnectionString;
mani replied to dipa ahuja on 01-Feb-12 03:18 AM
hi..thanks for u r reply..but how can i open that connection string after that??

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
  <add key="name" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
  </appSettings>
</configuration>
 
 
string s = ConfigurationSettings.AppSettings["name"].ToString();
dipa ahuja replied to mani on 01-Feb-12 03:31 AM
You just need to add the app.config file and it will be added same way as new form

now add the connection string here inside <appsettings>

 <add key="name" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/> 

here name is hte name of connstring and value is the connectionstring of your database

you can add any no. of connectionstring by using the add tag and at key you can give any name 

 <add key="conn1" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"/> 
 <add key="conn2" value="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database2.mdf;Integrated Security=True;User Instance=True"/>