我是C#的新手。我不明白为什么构造函数(constr)和_test1在这里出错? 有人可以给我一个谅解吗?
namespace ScratchPad
{
class loading
{
public string _text1 = @"C:\Users\me\Documents\Defect DB\noemi.xlsx";
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _text1 + ";Extended Properties=\"Excel 12.0 XML;HDR=YES;IMEX=1\";";
OleDbConnection con = new OleDbConnection(constr);
var selectStatement = String.Format("Select * From [{0}$]", "excel");// _test2 is not working.
OleDbDataAdapter adaptor = new OleDbDataAdapter(selectStatement, con);
con.Open(); // if i leave _test1 like that then, this will fail. private string _text1;
DataTable table = new DataTable();
adaptor.Fill(table);
}
}
答案 0 :(得分:0)
尝试将代码放在类的构造函数中,但请记住,只有在通过代码行创建Loading实例时才会触发代码。加载myloading = new Loading()。另外,请在装载时将L大写。它是正确的类命名约定。
namespace ScratchPad
{
class Loading
{
public string _text1;
public string constr;
public OleDbConnection con;
public string selectStatement;
public DataTable table;
public Loading()
{
string _text1 = @"C:\Users\me\Documents\Defect DB\noemi.xlsx";
constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _text1 + ";Extended Properties=\"Excel 12.0 XML;HDR=YES;IMEX=1\";";
con = new OleDbConnection(constr);
selectStatement = String.Format("Select * From [{0}$]", "excel");// _test2 is not working.
OleDbDataAdapter adaptor = new OleDbDataAdapter(selectStatement, con);
con.Open(); // if i leave _test1 like that then, this will fail. private string _text1;
table = new DataTable();
adaptor.Fill(table);
}
}
}