Peter Peer
Peter Peer

Reputation: 41

Error: A field initializer cannot reference the non-static field, method, or property

I can't find a solution for the following:

Code:

class ApiData

{ SqlCeConnection conn = new SqlCeConnection(@"Data Source=C:\Users\Peter\Documents   \db.sdf;");

SqlCeCommand cmd = null;
    SqlCeDataReader rdr = null;
    public string code()
    {
        conn.Open();
        cmd = conn.CreateCommand();
        cmd.CommandText ="SELECT code FROM Charakter WHERE id=1";
        rdr = cmd.ExecuteReader();
        rdr.Read();
        string selected = rdr.GetString(0);
        conn.Close();
        return (selected);
    }
class Data{
  ApiData g= new ApiData();
    string vode = **g.code();**
}

Error:

A field initializer cannot reference the non-static field, method, or property

Upvotes: 1

Views: 15911

Answers (2)

Xameer
Xameer

Reputation: 31237

Try making the field static which was giving this issue

//INITIALLY this field was non-static 
//public string ConnectionString = "Data Source=ServerName;Initial Catalog=DBname;User Id=user_id;Password=password";

//Make this field static
public static string ConnectionString = "Data Source=ServerName;Initial Catalog=DBname;User Id=user_id;Password=password";
static SqlConnection sqlConnection = new SqlConnection(ConnectionString);

Hope this helps...

Upvotes: 1

Chris Sinclair
Chris Sinclair

Reputation: 23208

The initial values for fields need to use constants, static fields/methods/properties, or new instances. Instead, set it in your constructor:

class Data
{
    ApiData g;
    string vode;

    public Data()
    {
        g = new ApiData();
        vode = g.code();
    }
}

Upvotes: 7

Related Questions