【问题标题】:Update DataGridViewCheckBoxColumn checkbox on CellClick更新 CellClick 上的 DataGridViewCheckBoxColumn 复选框
【发布时间】:2019-04-18 12:41:43
【问题描述】:

我有一个带有 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 中的复选框更新其状态?

【问题讨论】:

    标签: vb.net datagridview


    【解决方案1】:

    试试这样:

    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 中使用 .CommitEdit()。这是正确的,如果不是,我为什么需要这样做?
    • 我可以确认您发现不需要该事件的地方。似乎 Validate 在没有它的情况下提交了值。
    • This: CommitEdit(DataGridViewDataErrorContexts.Commit) 在 DGV 未绑定或其 DataSource 是 dumb 源(基本 List(Of something) 时使用。当 DGV 是绑定,你应该/可以使用BindingSource.CurrencyManager 来更新一个值。但是,Me.Validate()(或Me.Validate(True),遵循表单的AutoValidate 设置)在这里会产生相同的效果
    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    相关资源
    最近更新 更多