Click here to Skip to main content
15,904,415 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i m doing a c# project and i have sql database,in each form i hv to connect to the database,how can i store the connection string in a class and use it as required
Posted

You don't have to. You can and should use the System.Configuration namespace:

C#
var connectionString = ConfigurationManager.ConnectionStrings["CONNECTIONSTRINGNAME"];


If you're intent on accessing this value through a class property, you can do the following:

C#
public class Foo
{
    public static string ConnectionString
    {
        get { return ConfigurationManager.ConnectionStrings["CONNECTIONSTRINGNAME"]; }
    }
}
 
Share this answer
 
If you have a connection to SQL, the connection string will be saved in setting file, You can access it like this whenever you need it:

C#
Properties.Settings.Default.ConncectionString
 
Share this answer
 
For Storing Connection String why are you using whole Class.
It requires Just one variable
C#
String ConnectionString="Enter Your Connection String Here";

After that Use that Variable Where you Want.:)
 
Share this answer
 
Comments
jim lahey 22-Nov-11 8:58am    
Hmmm.. hard-coding connection strings, a big no-no.
[no name] 22-Nov-11 9:55am    
Don't hard code connection strings
Himu from Orissa 22-Nov-11 11:47am    
i have to write this things in all forms but i want to write only once and use it whenever required
Sergey Alexandrovich Kryukov 22-Nov-11 17:51pm    
You are right, but the above code does allow you to do it "only once". It is very bad by other reasons though. This is the use of immediate constant which is a big no-no even if this is not a connection string, but with connection string this is a perfect crime. One will never be able to modify connection string, which makes the application perfectly ad-hoc. Also, this answer does not address a real problem, not answering the question.

Very bad; this answer gets my big fat 1.
--SA

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