Click here to Skip to main content
15,897,518 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
In Windows Forms I want to declare connection string globally for database.

I tried the following
XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>

    <add key="connectionString" value="data source=KK;database=Windows;user id=sa;password=pwd"/>
    
  </appSettings>
</configuration>


But ConfigurationManager is not available in Windows Forms

How to solve this
Posted
Comments
Vedat Ozan Oner 13-Feb-14 9:18am    
It is available. Add reference to 'System.Configuration' http://msdn.microsoft.com/en-us/library/wkze6zky.aspx

KUMAR619 wrote:
But ConfigurationManager is not available in Windows Forms
Since when? See http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings(v=vs.90).aspx[^].
 
Share this answer
 
same place where you globally add variables ... just under


C#
public Form1()
        {
            InitializeComponent();
        }

         SqlConnection cn = new SqlConnection(@"Connection string");



this although just global for this form, if you want to put it over all for all forms

SQL
public Form1()
        {
            InitializeComponent();
        }

       public SqlConnection cn = new SqlConnection(@"Connection string");



but i would not use put a connection string as public ... id rather get a get set method going
if you want to change it you only need to call the name you alreaddy set and call new connection like
C#
cn = new SqlConnection(@"new Connection string");
 
Share this answer
 
v2
Comments
Richard MacCutchan 13-Feb-14 10:49am    
Please use the correct <pre> tags around code snippets. See the code button above the editor window.
MashaJoey 14-Feb-14 1:08am    
will do
The following code is working fine.

C#
SqlConnection connection=
new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
 
Share this answer
 
v2

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