C# DataGridView删除行报错:当前项无法移除,求故障原因
解决DataGridView删除行时的“无当前项”报错问题
这个报错我之前也碰到过!核心问题在于你点击按钮单元格的时候,BindingSource的Current属性其实是null——因为DataGridView的CellContentClick事件触发时,当前行的选中状态并没有自动同步到绑定源的当前项,或者用户只是点了按钮但没真正选中整行,导致RemoveCurrent()找不到要删除的对象。
给你两种靠谱的解决方案:
方案1:手动绑定当前项到点击的行
通过设置BindingSource的Position属性,强制把当前项指向你点击的那一行,这样RemoveCurrent()就有明确的目标了:
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView2.Columns[e.ColumnIndex].Name == "Reject") { // 先检查行索引有效(避免点击表头),且绑定源有数据 if (e.RowIndex >= 0 && creditRequestsBindingSource.Count > 0) { // 把绑定源的当前位置设置为点击的行索引 creditRequestsBindingSource.Position = e.RowIndex; if (MessageBox.Show("Are you sure that you want to reject this bid?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { creditRequestsBindingSource.RemoveCurrent(); } } } }
方案2:直接通过索引删除目标项
不依赖Current属性,直接通过行索引拿到要删除的对象,调用Remove()方法,这个方法更直接,也更不容易出问题:
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (dataGridView2.Columns[e.ColumnIndex].Name == "Reject") { if (e.RowIndex >= 0 && creditRequestsBindingSource.Count > 0) { // 通过行索引获取要删除的绑定对象 var itemToRemove = creditRequestsBindingSource[e.RowIndex]; if (MessageBox.Show("Are you sure that you want to reject this bid?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { creditRequestsBindingSource.Remove(itemToRemove); } } } }
额外注意点:
- 永远要检查
e.RowIndex >= 0,因为点击列头的时候e.RowIndex会是-1,这时候操作会触发额外错误; - 如果你的DataGridView选中模式不是
FullRowSelect,用户可能只点击按钮而没选中整行,这时候上面的方案依然能正常工作,不需要强制改选中模式。
内容的提问来源于stack exchange,提问作者Suren
相关产品推荐
相关产品推荐

