【问题标题】:I want to count checked checkboxes on datagridview when click on the checkbox not on button click当单击复选框而不是单击按钮时,我想计算 datagridview 上的选中复选框
【发布时间】:2013-05-23 22:15:33
【问题描述】:

我想计算单击复选框时在 datagridview 中选中的复选框的数量。

这是我的代码:

Dim count1 As Integer = 0
For Each row As DataGridViewRow In dgvAtt.Rows
  If row.Cells(1).Value = True Then
    count1 += 1
  End If
Next

txtCnton.Text = count1

我已在 CellContentClick、CellValueChanged 和 CellStateChanged 中调用了上述过程,但计数不正确。

【问题讨论】:

  • 您确定 cell(1) 是您的复选框列吗? DataGridView 列从索引 0 开始。
  • 你说“它不正确计数”是什么意思?

标签: vb.net datagridview checkbox


【解决方案1】:

复选框的数量与您的预期不同可能有两个原因。最有可能的是,由于 datagridview 编辑控件在失去焦点时如何提交其值,因此复选框列的值滞后于复选框状态。

解决方法是按照here on MSDN. 的描述处理 CurrentCellDirtyStateChanged 事件

所以你的代码会变成这样:

Sub dataGridView1_CurrentCellDirtyStateChanged( _
    ByVal sender As Object, ByVal e As EventArgs) _
    Handles dataGridView1.CurrentCellDirtyStateChanged

    If dataGridView1.IsCurrentCellDirty Then
        dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
    End If 
End Sub

然后你的 CellValueChangedHander 变为:

Public Sub dataGridView1_CellValueChanged(ByVal sender As Object, _
    ByVal e As DataGridViewCellEventArgs) _
    Handles dataGridView1.CellValueChanged

    If dataGridView1.Columns(e.ColumnIndex).Name = "CheckBoxes" Then 
        Dim count1 As Integer = 0
        For Each row As DataGridViewRow In dgvAtt.Rows
            If row.Cells("CheckBoxes").Value IsNot Nothing And row.Cells("CheckBoxes").Value = True Then
                count1 += 1
            End If
        Next

        txtCnton.Text = count1
    End If 
End Sub 

在上面的代码中,我还解决了计数不正确的第二个可能原因。在您的代码中,您通过单元格数组中的索引引用 datagridview 单元格。这几乎从来都不是最好的方法。相反,每一列都有一个可以在索引器中使用的名称。

【讨论】:

  • 我还对单元格值添加了一个空检查 - 我在 C# 中编写了我的测试代码,因此可能存在一些语法错误 - 同样在 C# 中,您需要转换单元格值为布尔值,这在 VB.Net 中可能是必需的
猜你喜欢
  • 2012-05-13
  • 2018-02-21
  • 1970-01-01
  • 2015-06-06
  • 1970-01-01
  • 2016-11-14
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多