Check which checkbox is checked with loop

18,711

Solution 1

You need to loop through the Controls collection of the control that has the Checkbox's added to it. Each Control object has a Controls collection. I would prefer a For Each loop in this scenario so I get the Control right away without having to get it using the Controls index If your CheckBoxes are added to the Panel directly, the easiest way to do it would be..

For Each ctrl As var In panel.Controls
    If TypeOf ctrl Is CheckBox AndAlso DirectCast(ctrl, CheckBox).IsChecked Then
        'Do Something
    End If
Next

Solution 2

I'm not very familiar with the VB.Net syntax, but in psudo-code:

ForEach CheckBox in ControlContainer
  DoSomething
Next

If you have all of your CheckBox controls in a single container - e.g. a Panel - then the above code would iterate each control that is a CheckBox.

Share:
18,711
Wilson
Author by

Wilson

Updated on July 24, 2022

Comments

  • Wilson
    Wilson almost 2 years

    What would be the syntax to check inside a visual basic form panel for checkboxes and find which are checked? I understand how I Could use a for loop and an if statement, but I'm confused as to the syntax to check for each checkbox. for example:

    Dim i As Integer
    For i = 1 To 10
        'Here is where my code would go. 
        'I could have ten checkboxes named in sequence (cb1, cb2, etc), 
        'but how could I put i inside the name to test each checkbox?
    Next
    
  • Wayne
    Wayne almost 8 years
    First line should be For Each ctrl As Control in panel.Controls
  • gkoul
    gkoul almost 6 years
    I think instead of .IsChecked you should just write .Checked