Setting Checkboxes to True by a value

CharlieMay

Active member
Joined
Jul 17, 2009
Messages
25
Location
Indiana
Programming Experience
10+
OK, I did this once before but I can't find the code where I did it.

I have 4 checkboxes and I want to assign them each a value like:
Checkbox1(1)
CheckBox2(2)
CheckBox3(4)
CheckBox4(8)

So that the value in the parentheses total a certain value when checked.
Example, if CheckBox1 and CheckBox3 are checked, I get the value of 5

Later when I pull 5 from the database, I can use that number to iterate through the 4 checkboxes and set 1 and 3 to true.

I think I did this with an array but I can't for the life of me remember.

Then I called them with something like:

fore each ctrl in me.controls
if typeof(ctrl) is checkbox then
ctrl.checked = ... ????
end if

Any help is appreciated... I've searched the net and even scanned 3 different computers that may contain that source code and have not had any luck finding it.
 
I'd be inclined to use a Dictionary for this:
VB.NET:
Public Class Form1

    Private checkBoxes As Dictionary(Of Integer, CheckBox)

    Private Sub Form1_Load() Handles MyBase.Load
        Me.checkBoxes.Add(1, Me.CheckBox1)
        Me.checkBoxes.Add(2, Me.CheckBox2)
        Me.checkBoxes.Add(4, Me.CheckBox3)
        Me.checkBoxes.Add(8, Me.CheckBox4)
    End Sub

    Private Function GetCheckBoxState() As Integer
        Dim state As Integer = 0

        For Each key In Me.checkBoxes.Keys
            If Me.checkBoxes(key).Checked Then
                state = state Or key
            End If
        Next

        Return state
    End Function

    Private Sub SetCheckBoxState(ByVal state As Integer)
        For Each key In Me.checkBoxes.Keys
            Me.checkBoxes(key).Checked = ((state And key) = key)
        Next
    End Sub

End Class
 
Back
Top