1

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

bruntime
  • 371
  • 2
  • 13
Peter Peer
  • 41
  • 1
  • 1
  • 5
  • 1
    Duplicate of http://stackoverflow.com/questions/7400677/a-field-initializer-cannot-reference-the-non-static-field-method-or-property – zebrabox Jun 13 '12 at 13:16

2 Answers2

7

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();
    }
}
Chris Sinclair
  • 22,858
  • 3
  • 52
  • 93
  • "The initial values for fields need to use constants" - it's not as restrictive as that; they can also reference static fields, methods or properties. But the solution is right, +1. – Joe Jun 13 '12 at 13:22
  • thanks, I tried this before, but forgot the "string vcode;" line. I did too long nothing on c#^^ – Peter Peer Jun 13 '12 at 13:24
1

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

Zameer Ansari
  • 28,977
  • 24
  • 140
  • 219