Question Can I do this with a loop

QADUDE

Member
Joined
Dec 30, 2009
Messages
12
Programming Experience
3-5
I have an application which uses 26 checkboxes and requires a checkbox to be set to checked when its associatand button is pressed and all other checkboxes set to unchecked. The code I am using is shown below, not too elegent can I use for next loops to achieve the same.

Private Sub ButtB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtB.Click

CheckBox1.CheckState = CheckState.Unchecked
CheckBox2.CheckState = CheckState.Checked
CheckBox3.CheckState = CheckState.Unchecked
CheckBox4.CheckState = CheckState.Unchecked
CheckBox5.CheckState = CheckState.Unchecked
CheckBox6.CheckState = CheckState.Unchecked
CheckBox7.CheckState = CheckState.Unchecked
CheckBox8.CheckState = CheckState.Unchecked
CheckBox9.CheckState = CheckState.Unchecked
CheckBox10.CheckState = CheckState.Unchecked
CheckBox11.CheckState = CheckState.Unchecked
CheckBox12.CheckState = CheckState.Unchecked
CheckBox13.CheckState = CheckState.Unchecked
CheckBox14.CheckState = CheckState.Unchecked
CheckBox15.CheckState = CheckState.Unchecked
CheckBox16.CheckState = CheckState.Unchecked
CheckBox17.CheckState = CheckState.Unchecked
CheckBox18.CheckState = CheckState.Unchecked
CheckBox19.CheckState = CheckState.Unchecked
CheckBox20.CheckState = CheckState.Unchecked
CheckBox21.CheckState = CheckState.Unchecked
CheckBox22.CheckState = CheckState.Unchecked
CheckBox23.CheckState = CheckState.Unchecked
CheckBox24.CheckState = CheckState.Unchecked
CheckBox25.CheckState = CheckState.Unchecked
CheckBox26.CheckState = CheckState.Unchecked
End Sub
 
Something along these lines will do it for you.

VB.NET:
[FONT=Consolas][SIZE=2][FONT=Consolas][SIZE=2]     Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        For Each c As Control In Me.Controls
            If c.GetType.FullName = "System.Windows.Forms.CheckBox" Then
                If CType(c, CheckBox).Name <> "CheckBox1" Then
                    CType(c, CheckBox).Checked = True
                End If
            End If
        Next
    End Sub
[/SIZE][/FONT][/SIZE][/FONT]

You get the controls on form
You then check each to see if its a checkbox
if its a checkbox you see if the name is the one you want left unchecked
if its not the one you want unchecked, check it.
 
Back
Top