如何在遍历表单控件时检查复选框是否被选中

Dav*_*ard 1 vb.net forms checkbox

我试图为表单上的每个复选框设置一个注册表项,但在下面的代码块中,我收到错误'Checked' is not a member of 'System.Windows.Forms.Control'

有人可以帮我找出为什么我会收到此错误吗?

' Create the data for the 'Servers' subkey
Dim SingleControl As Control    ' Dummy to hold a form control
For Each SingleControl In Me.Controls
    If TypeOf SingleControl Is CheckBox Then
        Servers.SetValue(SingleControl.Name, SingleControl.Checked) ' Error happening here
    End If
Next SingleControl
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 5

在使用 Checked 属性之前,您应该将控件转换为 CheckBox。
您直接使用 Control 变量,并且此类型 (Control) 没有 Checked 属性

Dim SingleControl As Control    ' Dummy to hold a form control
For Each SingleControl In Me.Controls
    Dim chk as CheckBox = TryCast(SingleControl, CheckBox)
    If chk IsNot Nothing Then
        Servers.SetValue(chk.Name, chk.Checked) 
    End If
Next 
Run Code Online (Sandbox Code Playgroud)

更好的方法可能是使用 Enumerable.OfType

Dim chk As CheckBox
For Each chk In Me.Controls.OfType(Of CheckBox)()
    Servers.SetValue(chk.Name, chk.Checked) 
Next 
Run Code Online (Sandbox Code Playgroud)

这消除了将通用控件转换为正确类型并测试转换是否成功的需要