Winforms Grid Checkbox Single Selection

2 posts, 0 answers
  1. Craig Finnigan
    Craig Finnigan avatar
    14 posts
    Member since:
    May 2008

    Posted 30 Mar 2012 Link to this post

    I was having some trouble getting my checkbox slection to have a oncheck event that could be used to restrict the grid to have a single checkbox selected at any given time and process the change as soon as the value changed not after leaving the field. This is what I came up with.

    Private Sub rgridAffinityPrograms_CellEditorInitialized(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) Handles rgridAffinityPrograms.CellEditorInitialized
            Dim editor As RadCheckBoxEditor = TryCast(e.ActiveEditor, RadCheckBoxEditor)
            AddHandler (editor.ValueChanged), AddressOf editor_ValueChanged
    End Sub
     
    Private Sub editor_ValueChanged(ByVal sender As Object, ByVal e As EventArgs)
            rgridAffinityPrograms.EndEdit()
    End Sub
     
    Private Sub rgridAffinityPrograms_CellValueChanged(ByVal sender As System.Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) Handles rgridAffinityPrograms.CellValueChanged
            If e.ColumnIndex = 0 And sender.ToString = "Telerik.WinControls.UI.GridCheckBoxCellElement" Then
                Dim chk As GridCheckBoxCellElement = sender
                If chk.Value = True Then
                    For Each row As GridViewRowInfo In rgridAffinityPrograms.Rows
                        If row.Index <> e.RowIndex Then
                            row.Cells("IsSelected").Value = False
                        End If
                    Next
                End If
            End If
    End Sub
  2. Stefan
    Admin
    Stefan avatar
    2908 posts

    Posted 04 Apr 2012 Link to this post

    Hi Craig,

    Thank you for sharing your solution with the community.

    I would like to propose adding code which unsubscribes your from the ValueChanged event of the editor prior to subscribing to it, in order to avoid multiple subscriptions, since the editors in RadGridView are reused:
    Private Sub rgridAffinityPrograms_CellEditorInitialized(ByVal sender As Object, ByVal e As Telerik.WinControls.UI.GridViewCellEventArgs) Handles rgridAffinityPrograms.CellEditorInitialized
            Dim editor As RadCheckBoxEditor = TryCast(e.ActiveEditor, RadCheckBoxEditor)
            RemoveHandler (editor.ValueChanged), AddressOf editor_ValueChanged
            AddHandler (editor.ValueChanged), AddressOf editor_ValueChanged
    End Sub

    Another thing that you might do is keep the previously checked cell in a variable and reset just its state instead of iterating all cells in the column.

    I hope that you find this information useful. Let us know if we can be of assistance.
     
    Regards,
    Stefan
    the Telerik team
    RadControls for WinForms Q1'12 release is now live! Check out what's new or download a free trial >>
Back to Top