如何在C# Windows Forms应用中点击按钮打开文件浏览器选择Access文件
实现Windows Forms中选择Access文件并导出数据的功能
我正在用Windows Forms开发待办事项清单应用,对接MS Access数据库。需要实现点击loadButton时弹出文件浏览器选择Access文件,并将DataGrid中的待办事项导出到该文件中。现有代码如下:
using System.Data; using System.Windows.Forms; using System.Data.OleDb; using System.Diagnostics; namespace todolistApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataTable todoList = new DataTable(); bool isEditing = false; private void Form1_Load(object sender, EventArgs e) { todoList.Columns.Add("Title"); todoList.Columns.Add("Description"); todolistView.DataSource = todoList; } private void newButton_Click(object sender, EventArgs e) { titletextBox.Text = ""; descriptiontextBox.Text = ""; } private void editButton_Click(object sender, EventArgs e) { isEditing = true; titletextBox.Text = todoList.Rows[todolistView.CurrentCell.RowIndex].ItemArray[0].ToString(); descriptiontextBox.Text = todoList.Rows[todolistView.CurrentCell.RowIndex].ItemArray[1].ToString(); } private void deleteButton_Click(object sender, EventArgs e) { try { todoList.Rows[todolistView.CurrentCell.RowIndex].Delete(); } catch (Exception ex) { Console.WriteLine("Error: " + ex); } } private void button3_Click(object sender, EventArgs e) { if (isEditing) { todoList.Rows[todolistView.CurrentCell.RowIndex]["Title"] = titletextBox.Text; todoList.Rows[todolistView.CurrentCell.RowIndex]["Description"] = titletextBox.Text; } else { todoList.Rows.Add(titletextBox.Text, descriptiontextBox.Text); } titletextBox.Text = ""; descriptiontextBox.Text = ""; isEditing = false; } private void insertButton_Click(object sender, EventArgs e) { foreach (DataRow row in todoList.Rows) { string constring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"E:\Downloads\coding stuf\todolistApp\todolistApp\todolistDB.accdb\""; using (OleDbConnection con = new OleDbConnection(constring)) { using (OleDbCommand cmd = new OleDbCommand("INSERT INTO Table1 ([Title], [Description]) VALUES (@title,@description)", con)) { cmd.Parameters.AddWithValue("@title", row["Title"].ToString()); cmd.Parameters.AddWithValue("@description", row["Description"].ToString()); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } } MessageBox.Show("All rows inserted."); } private void loadButton_Click(object sender, EventArgs e) { } } }
解决方案
1. 核心实现逻辑
使用Windows Forms内置的OpenFileDialog控件弹出文件选择窗口,筛选Access格式文件;再封装数据导出方法,将DataTable中的待办事项写入选中的Access文件。同时修复原代码中的小问题,提升程序稳定性。
2. 修改后的完整代码
using System.Data; using System.Windows.Forms; using System.Data.OleDb; namespace todolistApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } DataTable todoList = new DataTable(); bool isEditing = false; private void Form1_Load(object sender, EventArgs e) { todoList.Columns.Add("Title"); todoList.Columns.Add("Description"); todolistView.DataSource = todoList; } private void newButton_Click(object sender, EventArgs e) { titletextBox.Text = ""; descriptiontextBox.Text = ""; } private void editButton_Click(object sender, EventArgs e) { if (todolistView.CurrentCell == null) return; isEditing = true; var currentRow = todoList.Rows[todolistView.CurrentCell.RowIndex]; titletextBox.Text = currentRow["Title"].ToString(); descriptiontextBox.Text = currentRow["Description"].ToString(); } private void deleteButton_Click(object sender, EventArgs e) { try { if (todolistView.CurrentCell != null) { todoList.Rows[todolistView.CurrentCell.RowIndex].Delete(); } } catch (Exception ex) { MessageBox.Show($"删除错误: {ex.Message}"); } } private void button3_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(titletextBox.Text)) { MessageBox.Show("请输入标题"); return; } if (isEditing && todolistView.CurrentCell != null) { var currentRow = todoList.Rows[todolistView.CurrentCell.RowIndex]; currentRow["Title"] = titletextBox.Text; currentRow["Description"] = descriptiontextBox.Text; // 修复原赋值错误 } else { todoList.Rows.Add(titletextBox.Text, descriptiontextBox.Text); } titletextBox.Text = ""; descriptiontextBox.Text = ""; isEditing = false; } private void insertButton_Click(object sender, EventArgs e) { if (todoList.Rows.Count == 0) { MessageBox.Show("没有数据可插入"); return; } string constring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""E:\Downloads\coding stuf\todolistApp\todolistApp\todolistDB.accdb"""; using (OleDbConnection con = new OleDbConnection(constring)) { con.Open(); using (OleDbCommand cmd = new OleDbCommand("INSERT INTO Table1 ([Title], [Description]) VALUES (@title,@description)", con)) { cmd.Parameters.Add("@title", OleDbType.VarChar); cmd.Parameters.Add("@description", OleDbType.VarChar); foreach (DataRow row in todoList.Rows) { cmd.Parameters["@title"].Value = row["Title"].ToString(); cmd.Parameters["@description"].Value = row["Description"].ToString(); cmd.ExecuteNonQuery(); } } con.Close(); } MessageBox.Show("All rows inserted."); } private void loadButton_Click(object sender, EventArgs e) { // 创建文件选择对话框 using (OpenFileDialog openFileDialog = new OpenFileDialog()) { // 设置筛选器,仅显示Access文件 openFileDialog.Filter = "Access数据库文件 (*.accdb)|*.accdb|旧版Access文件 (*.mdb)|*.mdb"; openFileDialog.Title = "选择Access数据库文件"; // 用户选择文件并确认后执行导出 if (openFileDialog.ShowDialog() == DialogResult.OK) { string selectedFilePath = openFileDialog.FileName; ExportDataToAccess(selectedFilePath); } } } // 封装数据导出逻辑 private void ExportDataToAccess(string filePath) { if (todoList.Rows.Count == 0) { MessageBox.Show("没有数据可导出"); return; } // 构建目标文件连接字符串 string constring = $"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=\"{filePath}\""; try { using (OleDbConnection con = new OleDbConnection(constring)) { con.Open(); // 假设目标文件已存在Table1表,结构为Title(文本)、Description(文本) using (OleDbCommand cmd = new OleDbCommand("INSERT INTO Table1 ([Title], [Description]) VALUES (@title,@description)", con)) { cmd.Parameters.Add("@title", OleDbType.VarChar); cmd.Parameters.Add("@description", OleDbType.VarChar); foreach (DataRow row in todoList.Rows) { cmd.Parameters["@title"].Value = row["Title"].ToString(); cmd.Parameters["@description"].Value = row["Description"].ToString(); cmd.ExecuteNonQuery(); } } con.Close(); MessageBox.Show("数据导出成功"); } } catch (Exception ex) { MessageBox.Show($"导出错误: {ex.Message}"); } } } }
3. 关键说明
OpenFileDialog的Filter属性限制可选文件类型,避免用户选择非Access文件- 新增
ExportDataToAccess方法封装导出逻辑,提升代码复用性 - 补充空数据判断、异常捕获,避免程序崩溃
- 修复原代码中
button3_Click里描述字段的赋值错误 - 优化
insertButton_Click中的数据库连接使用,避免循环内重复创建连接
内容的提问来源于stack exchange,提问作者welive.welove.welie
相关产品推荐
相关产品推荐

