success success - 2 months ago 7x Question

Avoid duplicate code when mapping an array to Controls

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?



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

When an array or List maps to a set of Controls, create/maintain an array of those controls so you can just use a loop:

Public Class Form1
    ' declaration
    Private d2b As CheckBox()

Important: Do not initialize in the declaration (i.e. list the controls). The controls do not exist yet, so you will have an array of Nothing and get a NullReferenceException when you reference one. 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)

Use an If statement if you never want the checks to be UNchecked via the loop. The same method(s) will work to map an array of Booleans:

Private boolAry(8) As Boolean
myChecks(n).Checked = boolAry(n)

In fact, the same concept can be used to map data from any array to set of controls.