1

我正在尝试为表单上的每个复选框设置一个注册表项,但在以下代码块中,我收到了错误'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
4

5 回答 5

4

在使用 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 

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

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

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

于 2013-04-08T10:02:50.030 回答
3

试试这个代码,

Dim SingleControl As Control
For Each SingleControl In Me.Controls
    If TypeOf SingleControl Is CheckBox Then
        'control does not have property called checked, so we have to cast it into a check box.
        Servers.SetValue(CType(SingleControl, CheckBox).Name, CType(SingleControl, CheckBox).Checked)         End If
Next SingleControl
于 2013-04-08T10:01:31.130 回答
2

CheckedCheckBox类的属性,而不是Control其父类。

您要么必须向下转换Control为 aCheckbox才能访问该属性Checked,要么必须将复选框存储为CheckBox集合而不是Control集合。

于 2013-04-08T10:03:29.347 回答
1

试试这个:

For Each SingleControl As Control In Me.Controls
    If TypeOf SingleControl Is CheckBox Then
        Dim auxChk As CheckBox = CType(SingleControl, CheckBox)
        Servers.SetValue(auxChk.Name, auxChk.Checked)
    End If
Next SingleControl
于 2013-04-08T10:08:23.897 回答
0

使用我的扩展方法获取表单上的所有控件,包括表单中其他容器内的控件,即面板、组框等。

<Extension()> _
Public Function ChildControls(Of T As Control)(ByVal parent As Control) As List(Of T)
    Dim result As New ArrayList()
    For Each ctrl As Control In parent.Controls
        If TypeOf ctrl Is T Then result.Add(ctrl)
        result.AddRange(ChildControls(Of T)(ctrl))
    Next
    Return result.ToArray().Select(Of T)(Function(arg1) CType(arg1, T)).ToList()
End Function

用法:

Me.ChildControls(Of CheckBox). _
    ForEach( _
        Sub(chk As CheckBox)
            Servers.SetValue(chk.Name, chk.Checked)
        End Sub)
于 2013-04-08T15:29:53.403 回答