Search code examples
c#databaseoopclassoledb

How to create a method in a class that would "connect to my Database" on calling?


Can someone please tell me how can I create a method in a class that would execute the following code on calling ???

OledbConnection con;
private void createcon()
{
    con = new OleDbConnection();

    string currentPath = Directory.GetCurrentDirectory();
    string DBPath = "";
    if (Directory.Exists(currentPath + @"\Database") == true)
    {
        DBPath = currentPath + @"\Database\SMAStaff.accdb";
    }
    else
    {
        for (int i = 0; i < 2; i++)
        {
            currentPath = currentPath.Remove(currentPath.LastIndexOf("\\"));
        }
        DBPath = currentPath + "\\Database\\SMAStaff.accdb";
    }
    con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
    "Persist Security Info = False;Jet OLEDB:Database Password=123";
}

This method is present on every form of my project so I think creating a class would be a better idea. I'm able to accomplish this but when I call

con.open()

nothing happens and an error is shown in the error window. The name con doesnot exist in the current context. I know what that means but I don't know how to get past it. I've tried to make "con" public and internal but still noting happens ... If someone could help with this I would be grateful ... Thank you


Solution

  • you can change the return type of method, and if you put this on new classes you must change private to public:

    public OledbConnection createcon()
    {
       OledbConnection con = new OleDbConnection();
    
        string currentPath = Directory.GetCurrentDirectory();
        string DBPath = "";
        if (Directory.Exists(currentPath + @"\Database") == true)
        {
            DBPath = currentPath + @"\Database\SMAStaff.accdb";
        }
        else
        {
            for (int i = 0; i < 2; i++)
            {
                currentPath = currentPath.Remove(currentPath.LastIndexOf("\\"));
            }
            DBPath = currentPath + "\\Database\\SMAStaff.accdb";
        }
        con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + DBPath + ";" +
        "Persist Security Info = False;Jet OLEDB:Database Password=123";
    
    
        return con;
    
    }
    

    So you can use like this: classInstance.createcon().open();