【问题标题】:'For' loop for analyzing CheckBoxes in a panel'For' 循环用于分析面板中的复选框
【发布时间】:2013-11-13 15:08:29
【问题描述】:

我必须分析 CheckBoxes 是否被选中。一个TabPage中有10个CB,按顺序命名(cb1、cb2、cb3..等)。

 For Each c As CheckBox In TabPage4.Controls
        If c.Checked Then
            hello = hello + 1
        End If
    Next

我已经尝试了上述方法,但它给了我一个未处理的异常错误。

An unhandled exception of type 'System.InvalidCastException' occurred in WindowsApplication2.exe 
Additional information: Unable to cast object of type 'System.Windows.Forms.Label' to type 'System.Windows.Forms.CheckBox'.

【问题讨论】:

  • 您遇到的确切错误是什么?
  • @nhgrif 这里是:WindowsApplication2.exe 中发生了“System.InvalidCastException”类型的未处理异常附加信息:无法将“System.Windows.Forms.Label”类型的对象转换为“类型” System.Windows.Forms.CheckBox'。

标签: vb.net visual-studio visual-studio-2012 for-loop checkbox


【解决方案1】:

在这种情况下可能没有必要,但有时您需要“按顺序”获取它们。这是一个例子:

    Dim cb As CheckBox
    Dim hello As Integer
    Dim matches() As Control
    For i As Integer = 1 To 10
        matches = Me.Controls.Find("cb" & i, True)
        If matches.Length > 0 AndAlso TypeOf matches(0) Is CheckBox Then
            cb = DirectCast(matches(0), CheckBox)
            If cb.Checked Then
                hello = hello + 1
            End If
        End If
    Next

【讨论】:

    【解决方案2】:

    由于页面上可能还有其他控件,因此您需要查看每个控件是否都是检查:

    For Each c As Control In TabPage4.Controls
        if Typeof c is CheckBox then
            if Ctype(c, Checkbox).Checked Then
                hello +=1
            End If
        End If
    Next
    

    根据您的 VS 版本,这可能有效(需要 LINQ):

    For Each c As CheckBox In TabPage4.Controls.OfType(Of CheckBox)()
         If c.Checked Then
            hello += 1                ' looks dubious
        End If
    Next
    

    编辑

    我猜你的 Ctype 部分有问题,因为你的数组所做的基本上就是将 Ctl 转换为 Check(CType 所做的),但以更昂贵的方式。如果你不喜欢 Ctype(并且不能使用第二种方式):

    Dim chk As CheckBox
    For Each c As Control In TabPage4.Controls
        if Typeof c is CheckBox then
            chk  =  Ctype(c, Checkbox)
            if chk.Checked Then
                hello +=1
            End If
        End If
    Next
    

    没有数组,没有额外的对象引用。

    【讨论】:

    • 程序运行正常,但不会改变 hello 的值。
    • 什么是hello 字符串、整数...?实际上是否有任何复选框被选中?你可以在IF... 上设置一个断点,看看出了什么问题,比如检测复选框。更新您的帖子以包含 hello 和您正在使用的循环
    • 你好是一个整数。是的,复选框被选中。我对您的代码进行了一些更改,它可以完美运行。
    【解决方案3】:

    我对@Plutonix 代码进行了一些更改并使其正常工作。代码如下:

    Dim n As Integer = 1
    For Each c As Control In TabPage4.Controls
            If TypeOf c Is CheckBox Then
                CBs(n) = c
                If CBs(n).Checked Then
                    hello = hello + 1
                End If
            End If
            n = n + 1
        Next
    

    Cbs(n) 是我在模块上创建的复选框数组。它将“c”复选框声明为 Cbs(n) 并对其进行分析。然后它将变量 n 加 1 并重新启动该过程,直到 TabPage 中不再有 CheckBox。

    【讨论】:

      猜你喜欢
      • 2020-08-25
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 2017-10-20
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      相关资源
      最近更新 更多