Vb.net 在CellClick上更新DataGridViewCheckBoxColumn复选框

Vb.net 在CellClick上更新DataGridViewCheckBoxColumn复选框,vb.net,datagridview,Vb.net,Datagridview,我有一个带有DataGridViewCheckBoxColumn列的DataGridView。单元格大小比复选框大,因此为了便于用户使用,我希望CellClick事件的作用与复选框本身被单击一样 目前,我在CellClick活动中这样做: If e.ColumnIndex = dgv.Columns("CONFIRM").Index Then If CBool(dgv.Item("CONFIRM", e.RowIndex).Value) = True Then

我有一个带有DataGridViewCheckBoxColumn列的DataGridView。单元格大小比复选框大,因此为了便于用户使用,我希望CellClick事件的作用与复选框本身被单击一样

目前,我在CellClick活动中这样做:

If e.ColumnIndex = dgv.Columns("CONFIRM").Index Then
        If CBool(dgv.Item("CONFIRM", e.RowIndex).Value) = True Then
            dgv.Item("CONFIRM", e.RowIndex).Value = False
        Else
            dgv.Item("CONFIRM", e.RowIndex).Value = True
        End If
End If
但是,直到单元格失去焦点后,复选框才真正改变状态。我看到了许多关于处理不同事件(CellValueChanged、CurrentCellDirtyStateChanged)(例如)和提交更改的建议:

If dgvDownloads.IsCurrentCellDirty Then
        dgvDownloads.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If
但是,这不起作用,dgv会闪烁,但复选框不会更改选中状态


单击包含单元格时,如何强制DataGridViewCheckBoxColumn中的复选框更新其状态?

请尝试以下操作:

Public Class FormDGV

    Private Sub FormDGV_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        With DataGridView1
            .Columns.Add(New DataGridViewCheckBoxColumn With {
                         .Name = "Confirm",
                         .HeaderText = "Confirm"})
        End With
    End Sub

    Private Sub DataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
        If DataGridView1.IsCurrentCellDirty Then
            DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If
    End Sub

    Private Sub DataGridView1_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellClick
        If CType(DataGridView1.Rows(e.RowIndex).Cells("Confirm").Value, Boolean) Then
            DataGridView1.Rows(e.RowIndex).Cells("Confirm").Value = False
        Else
            DataGridView1.Rows(e.RowIndex).Cells("Confirm").Value = True
        End If
        Validate()
    End Sub
End Class

谢谢,
Validate()
是缺少的部分。有趣的是,如果我使用Validate(),我似乎不需要在
CurrentCellDirtyStateChanged
中使用
.committedit()
。这是否正确,如果不正确,为什么我需要这样做?我可以确认您的发现,在不需要该事件的地方。似乎Validate没有提交值。这:
CommittedIt(DataGridViewDataErrorContexts.Commit)
用于DGV未绑定或其数据源为哑源(基本列表)时。DGV绑定时,您应该/可以使用
BindingSource.CurrencyManager
更新值。但是,
Me.Validate()
(或
Me.Validate(True)
,遵循表单的
AutoValidate
设置)会产生相同的效果。