无法分配连接字符串值

时间:2014-12-01 07:12:14

标签: configuration field sqlconnection

我得到了以下错误请帮助。 C#代码

string s2 = System.Configuration.ConfigurationManager.ConnectionStrings["conec"].ToString();
SqlConnection con = new SqlConnection(s2);

App.Config中

 

<add name="conec" connectionString ="Integrated Security=SSPI;Persist Security                         Info=False;Initial Catalog=PACS_ENG_NEW;Data Source=HCL-68\SQLEXPRESS"/>

错误

Error   1   A field initializer cannot reference the non-static field, method, or property 'PDS1.frm_sales.s2'  C:\Documents and Settings\admin\My Documents\Visual Studio 2008\Projects\PDS1\PDS1\Sales.cs 28  47  PDS1

1 个答案:

答案 0 :(得分:0)

这通常是因为您无法在字段初始值设定项中访问con,它是非静态的。

SqlConnection conec = null; 
string s2 = System.Configuration.ConfigurationManager.ConnectionStrings["conec"].ToString();
public constructor()
{
       conec = new SqlConnection(s2);
}

尝试如上所述。它会起作用。