我有一个数据“myTable”,它与DataGridView“dgv”绑定. DataGridView“dgv”有一个复选框列.我的目标是删除按钮事件中检查的行.数据表当然会更新.
现在我的代码只用于删除一行而不是多行.
现在我的代码只用于删除一行而不是多行.
感谢帮助.
private void btnDel_Click(object sender,EventArgs e) { try { if (dgv.RowCount>0) { foreach (DataGridViewRow row in dgv.Rows) { DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell; if (check.Value != null) { if ((bool)check.Value) { DaTarowView currentDaTarowView = (DaTarowView)dgv.CurrentRow.DataBoundItem; DaTarow daTarow = currentDaTarowView.Row; int n = dgv.CurrentRow.Index; int intID = Convert.ToInt32(dgv.Rows[n].Cells[0].Value); myTable.Rows.Remove(daTarow); dgv.DataSource = myTable; Int32 intVal = Convert.ToInt32(row.Cells[1].Value); if (intVal == intID) { check.Value = null; } } } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
解决方法
我找到了解决方案.错误是由
DaTarowView currentDaTarowView = (DaTarowView)dgv.CurrentRow.DataBoundItem;
currentDaTarowView不是选中的行.
正确的代码是:
List<DaTarow> toDelete = new List<DaTarow>(); for (int i = 0; i < dgv.Rows.Count; i++) { { DataGridViewRow row = dgv.Rows[i]; DataGridViewCheckBoxCell check = row.Cells[0] as DataGridViewCheckBoxCell; if (check.Value != null && (bool)check.Value) { DaTarow daTarow = (row.DataBoundItem as DaTarowView).Row; toDelete.Add(daTarow); } } } toDelete.ForEach(row => row.Delete());
谢谢大家的帮助.