c# - 组合框项目选择更改时重新加载 DataGridview
问题描述
我创建了一个具有 DataGrid 的表单,它是从 excel 文件加载的。我想在组合框中显示 excel 文件表名称。我找到了在我的组合框中显示 excel 工作表名称的解决方案。但是我希望当我更改我的组合框项目时,datagridview 填充取决于我更改我的组合框的 excel 表。[IMG] http://i67.tinypic.com/153l82v.jpg[/IMG] 我该怎么做?我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
using System.IO;
namespace excel2access
{
public partial class Form2 : Form
{
string FilePath;
string CB;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog OpenFD = new OpenFileDialog();
OpenFD.FileName = "";
OpenFD.Title = "Choose Excel file to Upload Data ";
OpenFD.DefaultExt = "xls";
OpenFD.Filter = "Ms-Excel Files (*.xls)|*.xls|All Files|*.*";
if (OpenFD.ShowDialog() == DialogResult.OK)
{
FilePath = OpenFD.InitialDirectory + OpenFD.FileName;//Code to get FullPath, Filename and extension
textBox1.Text = FilePath;
string excelConnStr = string.Empty;
OleDbCommand excelCommand = new OleDbCommand();
if (FilePath.EndsWith(".xlsx"))
{
//2007 Format
excelConnStr =string.Format("Provider=Microsoft.ACE.OLEDB.12.0; Data Source={0};Extended Properties='Excel 8.0;HDR=No'", FilePath);
}
else
{
//2003 Format
excelConnStr= string.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0};Extended Properties='Excel 8.0;HDR=No'", FilePath);
}
//Get the Sheets in Excel Workbook
OleDbConnection excelConn = new OleDbConnection(excelConnStr);
OleDbCommand cmdExcel = new OleDbCommand();
OleDbDataAdapter oda = new OleDbDataAdapter();
cmdExcel.Connection = excelConn;
excelConn.Open();
comboBox1.DataSource = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
comboBox1.DisplayMember = "TABLE_NAME";
comboBox1.ValueMember = "TABLE_NAME";
CB = comboBox1.DisplayMember;
DataTable dtsheet = new DataTable();
dtsheet = excelConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
OleDbDataAdapter da = new OleDbDataAdapter("select * from [" + comboBox1.Text + "]", excelConnStr);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
解决方案
您必须为 comboBox1 定义 SelectionIndexChanged 事件并从该事件重新绑定网格。
我必须建议您第一次加载网格时,然后将多个工作表数据存储在一个具有多个表的数据集中。
当用户更改下拉值然后从该数据集中获取数据时,您可以防止多个数据库命中。
推荐阅读
- html - Google Places API:自动完成属性不适用于开普敦郊区,但南非其他地区
- python - 在 AWS EC2 上使用 Python 中的 SQLAlchemy 连接到 Oracle 数据库
- html - 如何从 ejs 向 express.js 发送 put 和 delete HTTP 请求
- oracle - oracle db 返回额外的填充
- javascript - 如何在nodejs中路由到html文件?
- npm - “npm prune --no-production”作为“npm ci/install”命令替代
- postgresql - 使用 psql 客户端读取列,这些列是使用 JPA AttributeConverter 编写的
- ruby-on-rails - 使用 send_file 下载 txt 文件时,safari 和 chrome 浏览器无法解析它
- c++ - C ++ QT终止到父级
- css - 我怎样才能得到这种盒子阴影或轮廓?