Click here to Skip to main content
15,881,173 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i Have 5 to 6 classes in which i am using connection string in windows form application is there any method to declare it only once and use directly. can we use singleton class for this? please give some example
Posted

PutConnection string in app.config as
HTML
<configuration>
    <configsections>
    </configsections>
    <connectionstrings>
        <add name="dbConnection">
            connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\HREChk.mdf;Integrated Security=True;User Instance=True"
            providerName="System.Data.SqlClient" />
    </add></connectionstrings>
</configuration>

and access this as
C#
String connString = ConfigurationManager.ConnectionStrings["dbConnection"].ToString();

See this Example also
Connection string in app.config
 
Share this answer
 
One way to do that is to have a file for CONSTANTS and move all your constants in that file. This file will contain a static class and all the application wide constants can become public static members of this class.

Another way of doing this is to have it in application settings. Project properties->Settings. Here you can have the connectionstring and access it as:

C#
Properties.Settings.Default.CONSTRING
 
Share this answer
 
Comments
Neha89 19-Mar-12 4:58am    
Do you have any sample code for creating file for constants?
Add your connection string in app.config file & use second method of Rahul Rajat Singh's solution.
 
Share this answer
 
Comments
Neha89 19-Mar-12 4:57am    
i stored it in app.config but still


ConnectionStringSettingsCollection connectionStrings = ConfigurationManager.ConnectionStrings;
string connString = connectionStrings["Connect"].ToString();

this much part is repeated in all classes.
Belowing Code Help to you for making your connection string--------

SqlConnectionStringBuilder bu = new SqlConnectionStringBuilder();

bu.DataSource = "mySqlServer";

bu.InitialCatalog = "myDatabase";

bu.IntegratedSecurity = false;

bu.UserId = "UserName";

bu.Password = "myPassword";

SqlConnection Conn = new SqlConnection(bu.ConnectionString);
 
Share this answer
 
v2
As requested by the poster:

The file would look like: (contants.cs)

C#
namespace MyWinApplication
{
    static class Constants
    {
        public static string CONN_STRING = "the actual string";
        public static int MAX_USERS = 300;
        public static int MAX_DB_CONNECTIONS = 500;
    }
}


and the usage will be like:

C#
new SqlConnection(Constants.CONN_STRING);
 
Share this answer
 
 
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