【问题标题】:Check which checkbox is checked with loop检查哪个复选框被循环选中
【发布时间】:2017-12-11 23:43:40
【问题描述】:

在 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

【问题讨论】:

    标签: vb.net forms checkbox for-loop


    【解决方案1】:

    您需要遍历已添加 Checkbox 的控件的 Controls 集合。每个 Control 对象都有一个 Controls 集合。在这种情况下,我更喜欢 For Each 循环,因此我无需使用 Controls 索引即可立即获得 Control 如果您的 CheckBoxes 直接添加到 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
    

    【讨论】:

    • 第一行应该是For Each ctrl As Control in panel.Controls
    • 我认为你应该写 .IsChecked 而不是 .Checked
    【解决方案2】:

    我对 VB.Net 语法不是很熟悉,但在伪代码中:

    ForEach CheckBox in ControlContainer
      DoSomething
    Next
    

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

    【讨论】:

      【解决方案3】:

      试试这个:

      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
      

      【讨论】:

        猜你喜欢
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2014-03-02
        • 1970-01-01
        • 2013-06-23
        • 2022-03-03
        • 1970-01-01
        相关资源
        最近更新 更多