检查循环选中的复选框

时间:2012-05-11 22:59:53

标签: vb.net forms checkbox for-loop

在visual basic窗体面板中检查复选框并找到哪些选中的语法是什么?我理解我如何使用for循环和if语句,但我对于检查每个复选框的语法感到困惑。例如:

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

3 个答案:

答案 0 :(得分:8)

您需要遍历已添加Checkbox的控件的Controls集合。每个Control对象都有一个Controls集合。在这种情况下,我更喜欢For Each循环,因此我可以立即获得Control而无需使用Controls索引。如果您的CheckBox直接添加到Panel,最简单的方法就是..

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

答案 1 :(得分:2)

我对VB.Net语法不太熟悉,但是在psudo-code中:

ForEach CheckBox in ControlContainer
  DoSomething
Next

如果您将所有CheckBox控件放在一个容器中 - 例如Panel - 然后上面的代码将迭代 a CheckBox的每个控件。

答案 2 :(得分:0)

试试这个:

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