You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET中统计DataGridView勾选CheckBox数量结果少1如何解决?

错误原因

  • DataGridView的CellContentClick事件触发时,CheckBox的选中状态还未提交到单元格的Value属性中,本次点击的勾选状态不会被统计到,最终结果就会比实际勾选数量少1。
  • 若DataGridView开启了允许添加新行的配置,新行的CheckBox单元格值为DBNull,直接执行Convert.ToInt16转换会抛出类型转换异常。

修复代码

在统计前先手动提交单元格编辑内容,同时增加空值、新行判断逻辑即可:

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
    ' 提交当前单元格的编辑状态,将勾选状态同步到Value属性
    DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
    Dim kk As Integer = 0
    For Each row As DataGridViewRow In DataGridView1.Rows
        ' 跳过末尾的空白新行
        If row.IsNewRow Then Continue For
        Dim checkValue = row.Cells("chkCheck").Value
        ' 空值判断避免转换错误
        If checkValue IsNot Nothing AndAlso Convert.ToInt16(checkValue) = 1 Then
            kk += 1
        End If
    Next
    lblSelect.Text = kk
End Sub

内容的提问来源于stack exchange,提问作者lowkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 01:54:03