2

呼び出し時に次のコードを実行するクラスでメソッドを作成する方法を誰か教えてください???

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";
}

このメソッドは私のプロジェクトのすべてのフォームに存在するため、クラスを作成することをお勧めします。私はこれを達成することができますが、私が呼び出すと

con.open()

何も起こらず、エラー ウィンドウにエラーが表示されます。名前 con は現在のコンテキストに存在しません。それが何を意味するかはわかっているが、それを乗り越える方法がわからない。「詐欺」を公開および内部にしようとしましたが、それでも発生することに注意してください...誰かがこれを手伝うことができれば、私は感謝します...ありがとう

4

1 に答える 1

4

メソッドのreturnタイプを変更できます。これを新しいクラスに配置する場合は、privateを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;

}

したがって、次のように使用できます。classInstance.createcon().open();

于 2012-10-30T08:46:08.493 に答える