有人可以告诉我如何在类中创建一个方法来执行以下代码来调用???
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不存在于当前上下文中。我知道这意味着什么,但我不知道如何克服它。我试图让“骗局”公开和内部但仍然注意到...... 如果有人可以帮助我,我将不胜感激...... 谢谢
答案 0 :(得分:4)
您可以更改方法的返回类型,如果将其放在新类上,则必须将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();