Click here to Skip to main content
15,903,856 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i am making desktop application....i have made form inwhich i made 4 buttons ADD,SAVE,UPDATE,DELETE .I am using SQL SERVER 2008 database.i am able to connect data with SQL.Now the problem is for each button's coding i have to write the following coding again and again

SqlConnection con = new SqlConnection("Data Source=SW-PC-20;Initial Catalog=PSM;Integrated Security=True");


and when i copy the project from one system to another,I have change the data source every time for all forms which become time consuming........
can i have concept of connection string and how to use.
thanx in advance
regards
Posted

You can save the connection string in Application Settings[^] (See CP How To Use the Settings Class in C#[^])

In your code you can the do:

// Properties.Settings.Default.DatabaseSettings - Contains your connection string.
SqlConnection con = new SqlConnection(Properties.Settings.Default.DatabaseSettings);


This way, you have one connection string saved in the file "MyProgram.exe.config".
 
Share this answer
 
v2
Comments
yesotaso 15-May-11 6:36am    
5 + "Properties.Settings.Default.DatabaseSettings" is almost as long as the connection string itself :).
Kim Togo 15-May-11 7:46am    
Thanks :-) By the way. What is the longest variable the you can declare in C# ?
You can use the connections string property in app.config file;

XML
<configuration>
         <connectionStrings>
        <add name="studentConnectionString" connectionString=" Data Source=SW-PC-20;Initial Catalog=PSM;Integrated Security=True;Integrated Security=True;  providerName="System.Data.SqlClient"/>
    </connectionStrings>
</configuration>


In code behind, you can call this connection string using the code ,

XML
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["studentConnectionString"].ConnectionString);


After that you need to change the connection string part only. becouse you are refering using name only.

hop you got the idea. if you need more clarification,
please ping me.
 
Share this answer
 
Check out http://www.connectionstrings.com[^] for detailed explanation on using connection strings with various technologies.
 
Share this answer
 
Better way to do that you can make a single class for database connectivity.With the help of class object you can connect with the database.So the redundancy will be reduce.........
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900