开发者

How can we block the user from unchecking a DataGridView checkbox?

We have a DataGridViewCheckBox column bound to a boolean property in our class.

The property setter has some logic which says that under certain conditions a True flag cannot be changed, ie, it stays checked forever. This is on a per record basis. So the entire column can't be readonly, only certain rows.

Pseudo code:

Public Property Foo() As Boolean
    Get
       Return _Foo
    End Get
    Set(ByVal value As Boolean)
        If _Foo An开发者_Go百科d Bar And value = False Then
            //do nothing, in this scenario once you're true, you stay true
        Else
            _Foo = value
        End If
    End Set
End Property

Databinding is handling all of this fine, except that the checkbox is visibly cleared when it's clicked. Then, of course, when the binding / setter is fired (as you move off that cell) it is restored to its checked status per the underlying logic. Ultimately it doesn't matter too much but it's a clumsy UI.

How can we intercept the user's click and keep it checked?


I think he is asking how to "conditionally" stop it from being unchecked... not how to programmatically stop ALL unchecking from occurring as your example has shown

What you want to do is to use the CellFormatting and CellContentClick events.

In CellFormatting you want to make the cell that contains the selected item read only, this will stop you from "unchecking" it. Then you want to check to see if the current cell in the CellContentClick is true. If it is, then you have just changed this cell to be the new ticked box, so cycle through each row, turing the others off.


This does the job but are there more elegant solutions?

Private Sub Grid1ButtonClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles Grid1.CellClick

    //allow checking, but don't allow unchecking
    If Grid1.Columns("myColumn").Index = e.ColumnIndex Then
        Dim chkbox As DataGridViewCheckBoxCell = Grid1.CurrentCell
        chkbox.ReadOnly = True
        chkbox.Value = True
    End If

End Sub
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜