Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to require CheckedListBox to have at least one item selected

With the CheckListBox in VB.NET in VS2005, how would you make it compulsory that at least one item is selected?

Can you select one of the items at design time to make it the default?

What would be best way to handle the validation part of this scenario? When should the user be required to tick one of the boxes?

like image 239
CJ7 Avatar asked Sep 16 '25 04:09

CJ7


2 Answers

Either idea -- preventing the user from unchecking the last checked item, or validating that at least one item is checked before proceeding -- is fairly straightforward to implement.

How to prevent the user from unchecking the last checked item

1. Make sure at least one item is checked to begin with (e.g., in your form's Load event):

Private Sub frm_Load(ByVal sender As Object, ByVal e As EventArgs)
    clb.SetItemChecked(0, True) ' whatever index you want as your default '
End Sub

2. Add some simple logic to your ItemCheck event handler:

Private Sub clb_ItemCheck(ByVal sender As Object, ByVal e As ItemCheckEventArgs)
    If clb.CheckedItems.Count = 1 Then ' only one item is still checked... '
        If e.CurrentValue = CheckState.Checked Then ' ...and this is it... '
            e.NewValue = CheckState.Checked ' ...so keep it checked '
        End If
    End If
End Sub

How to validate that at least one item is checked

Private Sub btn_Click(ByVal sender As Object, ByVal e As EventArgs)
    ' you could also put the below in its own method '
    If clb.CheckedItems.Count < 1 Then
        MsgBox("You must check at least one item.")
        Return
    End If

    ' do whatever you need to do '
End Sub
like image 95
Dan Tao Avatar answered Sep 17 '25 19:09

Dan Tao


You can, but the user can always uncheck it.

The way I would do this would be on submit, loop through the checkbox items and make sure at least one of them was checked (break the loop after as your requirement is met, no need to process the rest of the list.)

If the check fails, make a custom validator visible. Required field validators don't work with Check List Boxes, but you can see how they implemented here:

http://www.codeproject.com/KB/webforms/Validator_CheckBoxList.aspx

like image 28
Ged Avatar answered Sep 17 '25 20:09

Ged