我正在尝试为表单上的每个复选框设置一个注册表项,但在下面的代码块中,我收到错误'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
答案 0 :(得分: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
这消除了将通用控件转换为正确类型的需要,并测试转换是否成功
答案 1 :(得分: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
答案 2 :(得分:2)
Checked
是CheckBox
类的属性,而不是Control
父级的属性。
您必须将Control
向下转换为Checkbox
才能访问该媒体资源Checked
,或者您必须将复选框存储为CheckBox
集合而不是Control
{1}}收集。
答案 3 :(得分: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
答案 4 :(得分: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)