Search code examples
c#connectionoledbsystem.io.file

Connection the access dynamic


I have one problem in my project. I need connection the data base of access (teste.accdb), but this connection I need changed consonant the name of computer and where is location the file.

string caminhoficheiro = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

OleDbConnection conexao = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ caminhoficheiro+"teste.accdb");
    OleDbCommand comando = new OleDbCommand();

but the problem is "+ caminhoficheiro+". The error is "A field initializer cannot reference the non-static field, method, or property 'Form1.caminhoficheiro "

If you can help thanks.


Solution

  • In short, the error means - you cannot use one instance variable to initialize another instance variable. In your example, you are using caminhoficheiro to initialize another instance variable conexao

    Try this instead...

    OleDbConnection conexao = new OleDbConnection(string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}teste.accdb", Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)));
    OleDbCommand comando = new OleDbCommand();
    

    This way, you are getting rid of the one of the fields. There are few other ways to solve this (like constructor-based setting, etc.) but this is the fix with minimal change to your existing code.