选中DataGridView行修改值后点击更新,DataGridView未同步Access数据问题
问题分析与修复方案
核心问题
代码虽执行了更新语句并调用DisplayData()刷新列表,但存在几个导致DataGridView不更新的隐患:
- 未验证数据库更新是否真的成功(即使ID错误或SQL执行失败,仍会弹出成功提示)
- 数据库连接管理不规范,可能存在连接泄漏或状态异常
- 未强制DataGridView刷新数据
具体修复步骤
1. 验证更新操作的实际执行结果
修改UpdateButton_Click方法,通过ExecuteNonQuery()的返回值判断是否真的有记录被更新,避免误提示:
private void UpdateButton_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(ValueTextBox.Text) || string.IsNullOrEmpty(TypeTextBox.Text)) { MessageBox.Show("Please Select Record to Update"); return; } // 使用using自动释放连接和命令资源,避免泄漏 using (var con = new OleDbConnection("你的数据库连接字符串")) using (var cmd = new OleDbCommand("update Sflorotype set Sflorovalues=@value,Sflorotypes=@type where ID=@id", con)) { cmd.Parameters.AddWithValue("@id", ID); cmd.Parameters.AddWithValue("@value", ValueTextBox.Text); cmd.Parameters.AddWithValue("@type", TypeTextBox.Text); con.Open(); int affectedRows = cmd.ExecuteNonQuery(); if (affectedRows > 0) { MessageBox.Show("Record Updated Successfully"); DisplayData(); ClearData(); } else { MessageBox.Show("No record was updated. Check if the selected ID is valid."); } } }
2. 优化DisplayData方法,确保数据刷新
修改DisplayData方法,使用using管理DataAdapter,同时先解绑再重新绑定数据源,避免缓存问题:
private void DisplayData() { using (var con = new OleDbConnection("你的数据库连接字符串")) { DataTable dt = new DataTable(); using (var adapt = new OleDbDataAdapter("select * from Sflorotype", con)) { adapt.Fill(dt); } // 先解绑数据源再重新绑定,清除旧缓存 dataGridViewList.DataSource = null; dataGridViewList.DataSource = dt; // 强制刷新控件 dataGridViewList.Refresh(); } }
3. 确保ID变量作用域正确
确认ID是类的成员变量(而非局部变量),需在类顶部声明:
private int ID = 0;
4. 优化行点击事件的空值判断
避免单元格值为null时抛出异常,修改dataGridViewList_RowHeaderMouseClick方法:
private void dataGridViewList_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { var idCell = dataGridViewList.Rows[e.RowIndex].Cells[0].Value; var valueCell = dataGridViewList.Rows[e.RowIndex].Cells[1].Value; var typeCell = dataGridViewList.Rows[e.RowIndex].Cells[2].Value; if (idCell != null) ID = Convert.ToInt32(idCell.ToString()); if (valueCell != null) ValueTextBox.Text = valueCell.ToString(); if (typeCell != null) TypeTextBox.Text = typeCell.ToString(); }
额外注意事项
替换代码中的"你的数据库连接字符串"为实际的数据库连接字符串,避免使用全局连接对象,减少连接泄漏风险。
内容的提问来源于stack exchange,提问作者sahil ajmeri
相关产品推荐
相关产品推荐

