Search code examples
vb.netcheckboxstatechecksum

A sort of CRC to determine if Checkboxes have changed


VB2010. I have a form with about 25 checkboxes that the user can turn on or off. When they click OK a pretty big process ensues. However if the state of the checkboxes does not change from form load to pressing the OK button then there is nothing to update.

What I used to do in VB6 was calculate a cheksum on load based on iterating through all checkboxes in an array as so:

cheksum = checksum + (2^i) 

where i was the checkbox elements index and was unique just by definition.

When the user clicked on the OK button I would again calculate the checksum and if equal to the load checksum then I would do nothing.

So with .NET I am trying to do the same but having trouble coming up with a routine that would tell me if the .Checked state of the collection of checkboxes was the same on load as it is on button click. I don't have an array anymore just a bunch of uniquely named checkboxes.

Update: Thanks to Jim Mischel suggestions. I took the base code and instead of passing in the parameters I chose to make it more hard coded since I will only be using it in one module. It looks something like:

Private Function GetCrc() As Integer
    'we create a list of the checkboxes in the form
    Dim boxList As New List(Of CheckBox)
    boxList.Add(chkStates)
    boxList.Add(chkWorld)
    boxList.Add(chkCountries)

    'convert the list to an array of checkboxes
    Dim boxes() As CheckBox = boxList.ToArray

    'calculate the checksum
    Dim checkSum As Integer = 0
    For i As Integer = 0 To boxes.Length - 1
        If boxes(i).Checked Then
            checkSum = checkSum + (1 << i)
        End If
    Next i
    Return checkSum
End Function

Solution

  • You'll have to write code that creates a collection that you can loop over. I hope my rusty Visual Basic is understandable . . .

    public Function GetCheckboxChecksum(ParamArray boxes() as Checkbox)
        Dim Checksum as Integer = 0
        For i as integer = 0 to boxes.Length - 1
            If boxes(i).Checked Then
                Checksum = Checksum + (1 << i)
            End If
        Next I
        Return Checksum
    End Function
    
    ' To call it
    Dim Sum as Integer = GetCheckboxChecksum(cb1, cb2, cb3, cb4, cb5)