Wilson
Wilson

Reputation: 8768

Check which checkbox is checked with loop

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

Upvotes: 2

Views: 20320

Answers (3)

Abiodun Ojo
Abiodun Ojo

Reputation: 1

Try this :

Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            If CheckBoxList1.Text = "" Then
                do/display something
                Exit Sub
            Else
                For Each item As ListItem In CheckBoxList1.Items
                    If item.Selected Then
                        do/display something
                    End If
                Next
            End If
        End Sub

Upvotes: 0

IAbstract
IAbstract

Reputation: 19881

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.

Upvotes: 2

phixed
phixed

Reputation: 488

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

Upvotes: 8

Related Questions