c# - 错误:ConnectionString 属性尚未初始化
问题描述
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 工作表名称
解决方案
您的代码需要很少的修复:
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 语句以初始化您的连接字符串;)
推荐阅读
- angular - IdentityServer4 - Angular 如何将默认登录页面更改为 Angular 组件
- python-3.x - 安装 Kivy 模块时出错
- javascript - 在不同的函数中重复变量声明
- java - Windows 10 上的 JDK 提取和安装错误问题
- python - 从 Skopt 中的检查点恢复 gp_minimize 进程
- postgresql - pgp_sym_encrypt postgres 性能问题
- c# - SessionState cookieName 重命名 Asp.net_Session_ID 使会话无效 ["CaptchaVerify"]
- sqlite - SQLite FTS4 增强的查询语法行为(使用括号)
- sql - 如何在 hibernate native(createNative) 查询中编写 IN 子句?
- c# - 使用 TPL 在多个不同线程上创建单例对象