Limiting checkboxes - only check 2 of 5 - help needed

  • Thread starter Thread starter Patrick
  • Start date Start date
P

Patrick

Hello - I am designing a form that only allows 2 checkboxes to be checked
out of a series of checkboxes. However, checkedchanged and checkstatechanged
both act when the box is clicked on. I want only 2 boxes clicked, and if
another is selected nothing happens until one is unselected.

I tried keeping track of how many were checked then turning off all the
checkboxes, but that didn't seem right or allow changes. Also, if this could
be done easier with radiobuttons or something, hey, I'm all ears!
 
The following assumes 4 checkboxes on the form, with only two
selections allowed at a time. It's not sexy, but it gets the job done.


Private Sub AllBoxes_CheckedChanged(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged,
CheckBox2.CheckedChanged, CheckBox3.CheckedChanged,
CheckBox4.CheckedChanged
' Count the # of checked boxes
Dim qty As Int16 = 0
Dim cb As CheckBox
For Each cb In Me.Controls
If cb.Checked Then
qty += 1
End If
Next
If qty = 2 Then
' Disable the rest
For Each cb In Me.Controls
If Not cb.Checked Then
cb.Enabled = False
End If
Next
Else
' Enable all
For Each cb In Me.Controls
cb.Enabled = True
Next
End If
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top