phillip87 phillip87 - 7 months ago 37 Question

Visual Basic- Loop to make listbox update as checkbox is checked

I'm having trouble having the listbox update as the checkbox is checked. I have a total of 8 "test_location" check boxes and I want the listbox to add items to "Steps_Queue_List" and store "1" in the "Test_Locations" array when the location is checked. Also want to clear the list when the checkbox is unchecked. This works so far but I would much prefer to learn how to make a loop for this:

Private Sub Location_CheckBox_1_CheckedChanged(sender As Object, e As EventArgs) Handles Location_CheckBox_1.CheckedChanged
If Location_CheckBox_1.Checked Then
Test_Locations(0) = 1
Steps_Queue_List.Items.Add("test for location" & 1, 1)

ElseIf Location_CheckBox_1.Checked = False Then
Test_Locations(0) = 0
End If
End Sub

Private Sub Location_CheckBox_2_CheckedChanged(sender As Object, e As EventArgs) Handles Location_CheckBox_2.CheckedChanged
If Location_CheckBox_2.Checked Then
Test_Locations(1) = 1
Steps_Queue_List.Items.Add("test for location" & 2, 2)

ElseIf Location_CheckBox_2.Checked = False Then
Test_Locations(1) = 0
End If
End Sub

Private Sub Location_CheckBox_3_CheckedChanged(sender As Object, e As EventArgs) Handles Location_CheckBox_3.CheckedChanged
If Location_CheckBox_3.Checked Then
Test_Locations(2) = 1
Steps_Queue_List.Items.Add("test for location" & 3, 3)

ElseIf Location_CheckBox_3.Checked = False Then
Test_Locations(2) = 0
End If
End Sub

Thanks in advance.

Answer Source

You don't need a loop but you can just handle everything in a single method.

Set the property Tag of your Checkboxes to a progressive value starting from 1 to 8 matching the text value you want to be displayed in the listboxes.

Then setup an event handler that manages all the CheckBoxChanged events for all the CheckBox.

In this event handler retrieve the tag and use it to address the array index and the listbox to update

' Handle all Checkbox changed with the same handler
Private Sub OnCheckBoxChanged(sender As Object, e As EventArgs) 
Handles Location_CheckBox_1.CheckedChanged,Location_CheckBox_2.CheckedChanged,

    ' Discover which checkbox has been clicked
    Dim chk = DirectCast(sender, CheckBox)

    ' Now read the value of the Tag property of that checkbox
    Dim idx = Convert.ToInt32(chk.Tag)
    If chk.Checked Then
        Test_Locations(idx - 1) = 1
        Steps_Queue_List.Items.Add("test for location" & idx, idx)
        Test_Locations(idx - 1) = 0
    End If
End Sub
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download