DataGridView行转移后部分行无法删除的技术求助
问题分析与解决方案
核心问题
- 从dataGridView1转至dataGridView2时删除不全:你通过单元格0的复选框判断要转移的行,但删除时操作的是
SelectedRows(行选中集合),复选框打勾的行未必是选中状态,导致部分应删除的行没被处理。 - 从dataGridView2转至dataGridView1时删除混乱:在遍历
dataGridView2.Rows的循环里嵌套遍历删除行,遍历集合时直接修改集合会导致迭代器跳过元素,删不干净。
修正后的代码
从dataGridView1转移到dataGridView2的按钮事件
private void button2_Click(object sender, EventArgs e) { // 先收集所有需要转移的行,避免遍历原集合时修改导致异常 List<DataGridViewRow> rowsToMove = new List<DataGridViewRow>(); foreach (DataGridViewRow item in dataGridView1.Rows) { // 先判断复选框值不为空,避免空引用报错 if (item.Cells[0].Value != null && (bool)item.Cells[0].Value == true) { rowsToMove.Add(item); // 复制行数据到dataGridView2 int n = dataGridView2.Rows.Add(); dataGridView2.Rows[n].Cells[0].Value = false; dataGridView2.Rows[n].Cells[1].Value = item.Cells[1].Value?.ToString(); dataGridView2.Rows[n].Cells[2].Value = item.Cells[2].Value?.ToString(); dataGridView2.Rows[n].Cells[3].Value = item.Cells[3].Value?.ToString(); dataGridView2.Rows[n].Cells[4].Value = item.Cells[4].Value?.ToString(); dataGridView2.Rows[n].Cells[5].Value = item.Cells[5].Value?.ToString(); dataGridView2.Rows[n].Cells[6].Value = item.Cells[6].Value?.ToString(); dataGridView2.Rows[n].Cells[7].Value = item.Cells[7].Value?.ToString(); } } // 批量删除已转移的行 foreach (DataGridViewRow row in rowsToMove) { if (!row.IsNewRow) dataGridView1.Rows.Remove(row); } }
从dataGridView2转移到dataGridView1的按钮事件
private void button3_Click(object sender, EventArgs e) { List<DataGridViewRow> rowsToMove = new List<DataGridViewRow>(); foreach (DataGridViewRow item in dataGridView2.Rows) { if (item.Cells[0].Value != null && (bool)item.Cells[0].Value == true) { rowsToMove.Add(item); // 复制行数据到dataGridView1 int n = dataGridView1.Rows.Add(); dataGridView1.Rows[n].Cells[0].Value = true; dataGridView1.Rows[n].Cells[1].Value = item.Cells[1].Value?.ToString(); dataGridView1.Rows[n].Cells[2].Value = item.Cells[2].Value?.ToString(); dataGridView1.Rows[n].Cells[3].Value = item.Cells[3].Value?.ToString(); dataGridView1.Rows[n].Cells[4].Value = item.Cells[4].Value?.ToString(); dataGridView1.Rows[n].Cells[5].Value = item.Cells[5].Value?.ToString(); dataGridView1.Rows[n].Cells[6].Value = item.Cells[6].Value?.ToString(); dataGridView1.Rows[n].Cells[7].Value = item.Cells[7].Value?.ToString(); } } // 删除已转移的行 foreach (DataGridViewRow row in rowsToMove) { if (!row.IsNewRow) dataGridView2.Rows.Remove(row); } SelectedRowTotal(); }
额外优化点
- 增加了空值判断:避免复选框未点击时
Value为null导致的强制类型转换异常。 - 使用
?.ToString():防止单元格值为null时调用ToString()报错。 - 先收集后操作:统一处理转移和删除,避免遍历集合时修改集合引发的迭代异常或元素跳过问题。
内容的提问来源于stack exchange,提问作者elbays
相关产品推荐
相关产品推荐

