VB.NET中DataGridView复选框勾选加行索引、取消移除的实现
问题分析
你的原有代码存在以下几处逻辑错误:
- 逻辑冗余:不需要遍历所有行,当前事件触发的就是被点击的行,直接取
e.RowIndex对应的行即可,遍历会导致逻辑混乱 - 判断逻辑倒置:你当前在单元格值为未勾选状态时添加索引,和需求完全相反;且
Is关键字用于引用类型比较,值类型比较要换Equals或者直接转布尔判断 - 移除方法用错:
RemoveAt参数是列表自身的元素下标,不是你要删除的行索引值,要删除指定行号应该用Remove方法 - 取值时机错误:DataGridView的复选框单元格点击后,默认需要失去焦点才会提交值变更,直接读
Value拿到的是修改前的旧值,需要先手动提交编辑
正确实现代码
这段代码需要放在DataGridView的CellContentClick事件中:
' 假设你的索引列表是类级别声明的,示例声明如下: ' Dim bList_indexes As New List(Of Integer) Private Sub dataGridNames_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dataGridNames.CellContentClick ' 仅处理复选框列的有效行点击 If e.ColumnIndex = chk_column.Index AndAlso e.RowIndex >= 0 Then Try ' 提前提交单元格编辑,获取最新的勾选状态 dataGridNames.CommitEdit(DataGridViewDataErrorContexts.Commit) Dim currentRowIdx As Integer = e.RowIndex Dim chkCell As DataGridViewCheckBoxCell = TryCast(dataGridNames.Rows(currentRowIdx).Cells(chk_column.Index), DataGridViewCheckBoxCell) If chkCell IsNot Nothing Then Dim isChecked As Boolean = CBool(chkCell.Value) If isChecked Then ' 勾选时添加索引,增加重复判断避免重复插入 If Not bList_indexes.Contains(currentRowIdx) Then bList_indexes.Add(currentRowIdx) End If Else ' 取消勾选时移除对应行索引 bList_indexes.Remove(currentRowIdx) End If End If Catch ex As Exception ' 按需添加异常处理逻辑 ' MessageBox.Show(ex.Message) End Try End If End Sub
补充说明
如果你给复选框列自定义了TrueValue/FalseValue(比如用1/0、"是"/"否"代替默认布尔值),把CBool(chkCell.Value)替换成和你设置的值匹配的判断逻辑即可。
内容的提问来源于stack exchange,提问作者elmund0
相关产品推荐
相关产品推荐

