Wednesday, July 08, 2009

Enforcing a minimum of one check mark

Good evening, ladies and gentlemen. Here's a little code I tossed off recently in the Computer:

So, here's how I made sure that at least one check box remains checked in one of my forms. A quick search didn't turn out any vb.net samples for doing this, so here is my version so that I will have a source of copy-paste the next time I google :P

Private Sub dlgViewImageHistogram_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  chkRed.AutoCheck = False
  chkGreen.AutoCheck = False
  chkBlue.AutoCheck = False
  chkIntensity.AutoCheck = False
  chkIntensity.Checked = True
End Sub

Private Sub checkColor_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles _
chkRed.Click, chkGreen.Click, chkBlue.Click, chkIntensity.Click
  Dim checkCount As Integer
  For Each chkBox As Control In pnlChannels.Controls
    If Not TypeOf chkBox Is CheckBox Then Continue For
    checkCount = IIf(CType(chkBox, CheckBox).Checked, checkCount + 1, checkCount)
  Next

  If checkCount = 1 And sender.checked = True Then
    Exit Sub
  Else
    sender.checked = Not sender.checked
  End If

End Sub


Basically, you need to set the AutoCheck property of the checkboxes to 'false' to take over control of the setting of the 'Checked' property.
Also, make sure that you have at least one check box checked. I have put all the checkboxes in a Panel control. Maybe there's a better way of grouping the check boxes, but I haven't read up on it.

No comments: