如何在Windows窗体中全局声明我的连接字符串

如何在Windows窗体中全局声明我的连接字符串

问题描述:

在Windows窗体中我想为数据库全局声明连接字符串。



我尝试了以下

In Windows Forms I want to declare connection string globally for database.

I tried the following

<?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>





但是Windows窗体中没有ConfigurationManager



如何解决这个



But ConfigurationManager is not available in Windows Forms

How to solve this

KUMAR619写道:
KUMAR619 wrote:

但是ConfigurationManager在Windows窗体中不可用

But ConfigurationManager is not available in Windows Forms

从什么时候开始?请参阅 http://msdn.microsoft.com/ en-us / library / system.configuration.configurationmanager.connectionstrings(v = vs.90).aspx [ ^ ]。

Since when? See http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings(v=vs.90).aspx[^].


全球同一个地方添加变量......就在





same place where you globally add variables ... just under


public Form1()
        {
            InitializeComponent();
        }

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







this虽然这个表单只是全局的,但是如果你想把它全部用于所有表格






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

public Form1()
        {
            InitializeComponent();
        }

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







但我不会使用把连接字符串作为公共... id而不是得到一个get set方法去

如果你想改变它你只需要调用你设置的名称并调用新的连接喜欢




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

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


以下代码工作正常。



The following code is working fine.

SqlConnection connection=
new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);