string extension = Path.GetExtension(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 8.0;");
using (System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection())
{
switch (extension)
{
case ".xls":
string xlsconStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 8.0;";
con.ConnectionString = xlsconStr;
break;
case ".xlsx":
case ".xlsm":
string xlsxconStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 12.0;";
con.ConnectionString = xlsxconStr;
break;
}
using (System.Data.OleDb.OleDbCommand oconn = new System.Data.OleDb.OleDbCommand("SELECT * FROM [" + listBox1.SelectedIndex.ToString() + "$]", con))
{
// **There will be an error here**
// **The ConnectionString property has not been initialized.**
con.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
}
}
代码有什么问题?我的目的是在 listBox 上的 selectedItem 上绘制所有数据库,每当单击它时,它将填充 dataGridView
顺便说一句,所选项目来自 MSExcel worksheetName
答案 0 :(得分:0)
您的代码需要一点修复:
string extension = Path.GetExtension(openFileDialog1.FileName);
以前,您的GetExtension试图在您的连接字符串上查找扩展名,该方法无法实现,因为它是连接字符串而不是路径!
因此,已修复的代码应如下所示:
string extension = Path.GetExtension(openFileDialog1.FileName);
using (System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection())
{
switch (extension)
{
case ".xls":
string xlsconStr = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 8.0;";
con.ConnectionString = xlsconStr;
break;
case ".xlsx":
case ".xlsm":
string xlsxconStr = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + openFileDialog1.FileName + "'; Extended Properties=Excel 12.0;";
con.ConnectionString = xlsxconStr;
break;
}
using (System.Data.OleDb.OleDbCommand oconn = new System.Data.OleDb.OleDbCommand("SELECT * FROM [" + listBox1.SelectedIndex.ToString() + "$]", con))
{
con.Open();
System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oconn);
System.Data.DataTable data = new System.Data.DataTable();
adapter.Fill(data);
dataGridView1.DataSource = data;
}
}
现在您的代码将输入switch case语句以初始化您的连接字符串;)