-
Limiting Checkboxes
Hi Vbforms,
I have a question about checkboxes in Visual Basic. I have 6 Checkboxes available to select but i want to limit the amount a user can select to 4. What is the best way to do this? Can i simply grey out the other two after the 4 has been reached?
Then i want to check if the user has selcted 4 with a button click - How would i check that they have selected 4 not 3, 2 or just the 1
Currently i'm working on the idea (yes i'm pretty new to VB) but any code examples would be appreciated ^_^
Thanks
-
Re: Limiting Checkboxes
I don't know which variant of VB you mean, but the VBScript forum is not the right place.
Based on your previous post I assume VBA, so I have moved this thread to the 'Office Development/VBA' forum.
-
Re: Limiting Checkboxes
Hi Mate its not VBA im working on - just straight visual basic in visual studio
Thanks Phil
-
Re: Limiting Checkboxes
Which version of Visual Studio? (eg: 2010)
-
Re: Limiting Checkboxes
-
Re: Limiting Checkboxes
In that case... Thread moved to the 'VB.Net' (VB2002 and later) forum
-
Re: Limiting Checkboxes
What do you want to happen if the user tries to check a fifth box? Do you want to prevent it or do you want to uncheck one of the checked ones? I'm guessing the former, so here's a way to disable any unchecked boxes when the maximum number have already been checked and re-enable them if one is unchecked:
Code:
Private Const MAX_CHECKED_BOX_COUNT As Integer = 4
Private Sub CheckBoxes_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox6.CheckedChanged,
CheckBox5.CheckedChanged,
CheckBox4.CheckedChanged,
CheckBox3.CheckedChanged,
CheckBox2.CheckedChanged,
CheckBox1.CheckedChanged
'Get all the CheckBoxes.
Dim checkBoxes = Controls.OfType(Of CheckBox)().ToArray()
'Get the number of checked CheckBoxes.
Dim checkedBoxCount = checkBoxes.Count(Function(cb) cb.Checked)
'Unchecked CheckBoxes should be enabled if and only if the number of checked CheckBoxes is less than the maximum number allowed.
Dim enableUncheckedBoxes = checkedBoxCount < MAX_CHECKED_BOX_COUNT
'Get the unchecked CheckBoxes.
Dim uncheckedBoxes = checkBoxes.Where(Function(cb) Not cb.Checked)
'Enable or disable the unchecked CheckBoxes as appropriate.
For Each uncheckedBox In uncheckedBoxes
uncheckedBox.Enabled = enableUncheckedBoxes
Next
End Sub