Cannot assign connection string value

95 Views Asked by At

I am getting th efollowing error Please help. C# code

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

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

There are 1 best solutions below

0
On BEST ANSWER

This is generally happen because you can not access con in the field initializer,its non static.

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

Try as like above. It will work.