success success - 4 months ago 12
Vb.net Question

Get rid of duplicate code when traverse the array of bits in vb.net

I have a array of bit which has size of 8, I traverse the array of bit and update the checkbox of each corresponding bit based on whether the bit is zero or not. So far I have the following:

Dim btArr6 As BitArray = New BitArray(8)
......
......
If btArr6(0) = True Then
d2b0.Checked = True
End If
If btArr6(1) = True Then
d2b1.Checked = True
End If
If btArr6(2) = True Then
d2b2.Checked = True
End If
If btArr6(3) = True Then
d2b3.Checked = True
End If
If btArr6(4) = True Then
d2b4.Checked = True
End If
If btArr6(5) = True Then
d2b5.Checked = True
End If
If btArr6(6) = True Then
d2b6.Checked = True
End If
If btArr6(7) = True Then
d2b7.Checked = True
End If


I think it has duplicate code. I am thinking it would be better if I have something like d2b & I. However it is not right since it is not string. Any idea on how could I get rid of duplicate code?

Thanks

Answer

At the very least, this would be shorter:

d2b0.Checked = btArr6(0)
d2b1.Checked = btArr6(1)
...

No need to test the state unless you never want it to reset to unchecked this way. In that case you can use the single line form to at least lessen the cruft:

If btArr6(0) Then d2b0.Checked = True

Or create/maintain an array of CheckBox objects and then just loop:

' declaration
Private d2b As CheckBox()

Initialize it somewhere like form load:

d2b = New CheckBox() {CheckBox1, CheckBox2, CheckBox3, CheckBox4}

Then looping:

For n As Int32 = 0 To d2b.Count - 1
    d2b(n).Checked = btArr6(n)
Next

Use an If statement if you never want the checks to be UNchecked via the loop.