C# Winform应用中如何给DataGridView新增记录且不丢失原有数据
问题根源
你当前的代码每次执行查询时都会创建全新的DataTable对象,再直接赋值给DescriptiveGrid.DataSource,等于每次都用新的数据源替换原有绑定数据,所以之前加载的记录会被清空。
解决方案
将存储题目的DataTable改为窗体全局变量,每次查询到新数据后追加到全局DataTable中,再重新绑定到控件即可。同时建议你将原有字符串拼接SQL的写法改为参数化查询,避免SQL注入风险。
具体实现代码
首先在窗体类的级别定义全局存储表:
// 放在窗体类内部、所有方法外,作为全局变量 private DataTable _allSelectedQuestions = new DataTable();
然后修改你的查询绑定逻辑:
DataTable tempDt = new DataTable(); // 参数化查询避免SQL注入 string sql = "select top @QuestionCount * from DescriptiveQuestions where Difficulty_Level=@Diff and Chapter=@Chapter and Course=@Course order by newid()"; using (SqlCommand cmd = new SqlCommand(sql, c)) { cmd.Parameters.AddWithValue("@QuestionCount", QuestionsNumericUpDown.Value); cmd.Parameters.AddWithValue("@Diff", DiffComboBox.Text); cmd.Parameters.AddWithValue("@Chapter", ChapterComboBox.Text); cmd.Parameters.AddWithValue("@Course", CourseComboBox.Text); c.Open(); tempDt.Load(cmd.ExecuteReader()); c.Close(); } // 合并数据到全局表 if (_allSelectedQuestions.Columns.Count == 0) { // 首次加载直接复制结构和数据 _allSelectedQuestions = tempDt.Copy(); } else { // 后续追加新查询到的行 foreach (DataRow dr in tempDt.Rows) { _allSelectedQuestions.ImportRow(dr); } } // 刷新控件绑定 DescriptiveGrid.DataSource = null; DescriptiveGrid.DataSource = _allSelectedQuestions;
可选优化:避免重复题目
如果需要防止同一道题被重复添加到试卷中,假设你的题库表主键字段为QuestionId,可以把追加行的逻辑修改为:
foreach (DataRow dr in tempDt.Rows) { // 检查当前题目是否已经存在于全局表中 bool isExisted = _allSelectedQuestions.AsEnumerable() .Any(r => r["QuestionId"].ToString() == dr["QuestionId"].ToString()); if (!isExisted) { _allSelectedQuestions.ImportRow(dr); } }
其他说明
如果需要清空已选的所有题目,直接执行_allSelectedQuestions.Rows.Clear();后重新绑定控件即可。
内容的提问来源于stack exchange,提问作者numan bloch
相关产品推荐
相关产品推荐

