在CellClick上更新DataGridViewCheckBoxColumn复选框

时间:2019-04-18 12:41:43

标签: 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
            dgv.Item("CONFIRM", e.RowIndex).Value = False
        Else
            dgv.Item("CONFIRM", e.RowIndex).Value = True
        End If
End If

但是,直到单元格失去焦点之后,该复选框才真正改变状态。我已经看到许多有关处理不同事件(CellValueChanged,CurrentCellDirtyStateChanged)(例如http://www.codingeverything.com/2013/01/firing-datagridview-cellvaluechanged.html)并通过以下方式提交更改的建议:

If dgvDownloads.IsCurrentCellDirty Then
        dgvDownloads.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If

但是,这不起作用,dgv会闪烁,但复选框不会更改选中状态。

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

1 个答案:

答案 0 :(得分:2)

更像这样尝试:

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