Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace Sample2
{
    public class MyFunctions
    {
        string connstring = ConfigurationManager.ConnectionStrings["EpfConnectionString"].ConnectionString;
        SqlConnection con = new SqlConnection(connstring);  //error in connstring 
       
}
}


#Above is my class where it is showing error as Error 12 A field initializer cannot reference the non-static field, method, or property.
@error at SqlConnection con = new SqlConnection(connstring);

Below is my web.config code

C#
<connectionStrings>
    <add name="EpfConnectionString" connectionString="Data Source=ACS-MUMADHD-25\SQLEXPRESS;Initial Catalog=epf;Persist Security Info=True;User ID=sa;Password=sa2008" providerName="System.Data.SqlClient" />
  </connectionStrings>


Experts Please help...
Millions of thanks in advance
Posted
Updated 10-Aug-15 20:07pm
v4
Comments
Sinisa Hajnal 11-Aug-15 2:21am    
Put the initializing code in a constructor. Or some initialize method. Define SqlConnection _conn = null; and set it in the method. You don't need connection string at class level. You could also define const string connectionString = ... and use it throughout the class.

If you get an error message you don't understand, copy and paste it into Google - the chances are very good that someone else has met this before.
In your case loads of people have been confused by this one!
"A field initializer cannot reference the non-static field"[^]

If you have a look at the links, it explains the problem - you can't declare and set a class-level variable to a non-static value.

con is not inside a method, so it can't access non-static information in an initialiser (because it all has to be done before the class constructor is called)
Move the initialization into your class constructor, and you'll be fine:

C#
public class MyFunctions
    {
        string connstring = ConfigurationManager.ConnectionStrings["EpfConnectionString"].ConnectionString;
        SqlConnection con = null;
        public MyFunctions()
        {
            con = new SqlConnection(connstring);
        }
    }
 
Share this answer
 
v2
Comments
harshil gandhi 11-Aug-15 3:14am    
Thank you...#OriginalGriff
OriginalGriff 11-Aug-15 3:22am    
You're welcome!
C#
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["EpfConnectionString"].ConnectionString);
 
Share this answer
 
Comments
harshil gandhi 11-Aug-15 3:14am    
Many thanks...@Arasappan

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