Search code examples
vb.netlistviewcheckboxcheckboxlist

Make listview with checkboxes act like checkbox list


I need a checkbox list that I can add read-only items (hence using a listview so I can gray-out an item and keep a user from selecting it).

However, when I click the item, the checkbox doesn't toggle. But when I add the following code to the item click event,

Private Sub LVSubFiles_Click(sender As Object, e As EventArgs) Handles LVSubFiles.Click
        If LVSubFiles.Items(LVSubFiles.FocusedItem.Index).ForeColor <> Drawing.Color.Gray Then
            If LVSubFiles.Items(LVSubFiles.FocusedItem.Index).Checked = True Then
                LVSubFiles.Items(LVSubFiles.FocusedItem.Index).Checked = False
            Else
                LVSubFiles.Items(LVSubFiles.FocusedItem.Index).Checked = True
            End If
        End If
End Sub

But in this case when the user clicks on the checkbox rather than the item, nothing happens, as well selecting any other checkbox checks both the highlighted item and the checkbox of the new item selected.

Is there a way I can make the items act like a checkbox list? I've tried using Data Grid View, but i run into similar issues and a lot of code is based on the actions of this listview.


Solution

  • For those who find this question. I ultimately went with a hidden column which tracked "read only" items. Whenever the list would update the read-only tags would turn the item gray, but still enable it to be checked.

    In regard to how the list interacted with the user, I moved the action items into the two categories and this seems to be working smoothly. The user can select/deselect with a single click regardless of which part of the item is clicked.

    Private Sub dgvSubFiles_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSubFiles.CellContentClick
        If dgvSubFiles(dgvSubFiles.Columns("chkSubFiles").Index, dgvSubFiles.CurrentCell.RowIndex).Value = True Then
            dgvSubFiles(dgvSubFiles.Columns("chkSubFiles").Index, dgvSubFiles.CurrentCell.RowIndex).Value = False
        Else
            dgvSubFiles(dgvSubFiles.Columns("chkSubFiles").Index, dgvSubFiles.CurrentCell.RowIndex).Value = True
        End If
    End Sub
    
    Private Sub dgvSubFiles_SelectionChanged(sender As Object, e As EventArgs) Handles dgvSubFiles.SelectionChanged
        dgvSubFiles.ClearSelection()
    End Sub