How to check if a checkbox is checked when iterati

2019-08-15 03:03发布

问题:

I'm trying to set a registry key for every checkbox on a form, but in the following block of code, I'm receiving the error 'Checked' is not a member of 'System.Windows.Forms.Control'

Can somebody please help me find out why I'm getting this error?

' 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

回答1:

You should convert your control to a CheckBox before using the Checked property.
You use directly the Control variable and this type (Control) doesn't have a Checked property

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 

A better approach could be using Enumerable.OfType

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

this removes the need to convert the generic control to a correct type and test if the conversion was successfully



回答2:

Try this code,

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


回答3:

Checked is a property of the CheckBox class, not its Control parent.

You either have to downcast the Control into a Checkbox in order to access the property Checked or you have to store your checkboxes as a CheckBox collection not a Control collection.



回答4:

Try this:

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


回答5:

Use my extension method to get all controls on the form, including controls inside other containers in the form i.e. panels, groupboxes, etc.

<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

Usage:

Me.ChildControls(Of CheckBox). _
    ForEach( _
        Sub(chk As CheckBox)
            Servers.SetValue(chk.Name, chk.Checked)
        End Sub)