如何阻止重复值从TextBox进入绑定Access的DataGridView(C#.NET)
解决DataGridView重复录入问题的方案
核心问题分析
当前代码直接执行插入操作,未提前校验数据库中是否已存在相同的Sflorovalues与Sflorotypes组合记录,导致重复数据被插入,最终在DataGridView中显示重复值;同时代码存在SQL注入风险,需同步优化。
具体解决步骤
1. 插入前校验重复记录
在执行INSERT语句前,先查询数据库确认目标记录是否存在,仅当记录不存在时才执行插入:
private void AddButton_Click(object sender, EventArgs e) { try { // 提取并修剪输入值,避免空格干扰 string inputValue = ValueTextBox.Text.Trim(); string inputType = TypeTextBox.Text.Trim(); // 空值校验,防止插入无效数据 if (string.IsNullOrEmpty(inputValue) || string.IsNullOrEmpty(inputType)) { MessageBox.Show("请填写完整的数值和类型信息"); return; } // 使用using语句自动管理数据库连接资源 using (OleDbConnection connection = new OleDbConnection("provider=microsoft.ace.oledb.12.0;data source=F:\\Floro_sense\\Floros.mdb")) { connection.Open(); // 校验重复记录的参数化SQL string checkDuplicateSql = "SELECT COUNT(*) FROM Sflorotype WHERE Sflorovalues = ? AND Sflorotypes = ?"; using (OleDbCommand checkCmd = new OleDbCommand(checkDuplicateSql, connection)) { checkCmd.Parameters.AddWithValue("@value", inputValue); checkCmd.Parameters.AddWithValue("@type", inputType); int duplicateCount = (int)checkCmd.ExecuteScalar(); if (duplicateCount > 0) { MessageBox.Show("该记录已存在,无需重复添加"); return; } } // 执行参数化插入操作,规避SQL注入 string insertSql = "INSERT INTO Sflorotype(Sflorovalues, Sflorotypes) VALUES (?, ?)"; using (OleDbCommand insertCmd = new OleDbCommand(insertSql, connection)) { insertCmd.Parameters.AddWithValue("@value", inputValue); insertCmd.Parameters.AddWithValue("@type", inputType); insertCmd.ExecuteNonQuery(); MessageBox.Show("记录添加成功"); } // 刷新DataGridView数据 OleDbDataAdapter adapter = new OleDbDataAdapter("select * from Sflorotype", connection); DataTable table = new DataTable(); adapter.Fill(table); BindingSource bind = new BindingSource(); bind.DataSource = table; dataGridViewList.DataSource = bind; } } catch (Exception ex) { MessageBox.Show($"添加失败:{ex.Message}"); Console.WriteLine(ex.Message); } }
2. 额外优化建议
- 用
using语句管理数据库连接和命令对象,自动释放资源,避免连接泄漏。 - 加入输入值空值校验,防止无效空数据插入。
- 采用参数化查询彻底解决SQL注入风险,同时避免特殊字符导致的SQL语法错误。
- 若DataGridView数据量较大,可直接将新行添加到现有DataTable,无需重新查询全表以提升性能:
// 从现有数据源获取DataTable DataTable currentTable = (dataGridViewList.DataSource as BindingSource).DataSource as DataTable; // 创建新行并赋值 DataRow newRow = currentTable.NewRow(); newRow["Sflorovalues"] = inputValue; newRow["Sflorotypes"] = inputType; // 添加到DataTable自动刷新DataGridView currentTable.Rows.Add(newRow);
关键说明
通过插入前的重复校验,从源头阻止了重复数据进入数据库,DataGridView自然不会显示重复值;优化后的代码安全性、健壮性更强,能减少潜在异常问题。
内容的提问来源于stack exchange,提问作者sahil ajmeri
相关产品推荐
相关产品推荐

