问题
I need to loop through all Checkboxes on a form and get the Tag property for each. The Checkboxes are in Groupboxes, and nested Groupboxes. Code I have works for the main form, it is not getting the values from the Checkboxes in the Groupboxes
...
i = 0
For Each ctrl As Control In Me.Controls
If (TypeOf ctrl Is CheckBox) Then
'Resize array
ReDim Preserve g_str_Array(i)
'Add Tag to array
g_str_Array(i) = CStr(ctrl.Tag)
i += 1
End If
Next
...
回答1:
Here's a method that you can add to a form that provides access to every control on the form via the Tab order:
Public Iterator Function GetControls() As IEnumerable(Of Control)
Dim ctrl = GetNextControl(Me, True)
Do Until ctrl Is Nothing
Yield ctrl
ctrl = GetNextControl(ctrl, True)
Loop
End Function
Because that is an iterator, you can chain other LINQ methods to it. To get the Tag
of each CheckBox
into an array:
Dim checkBoxTags = GetControls().OfType(Of CheckBox)().
Select(Function(cb) CStr(cb.Tag)).
ToArray()
If you wanted to use this method for multiple forms then, rather than repeating the code in each of them, you can add a single extension method:
Imports System.Runtime.CompilerServices
Public Module FormExtensions
<Extension>
Public Iterator Function GetControls(source As Form) As IEnumerable(Of Control)
Dim ctrl = source.GetNextControl(source, True)
Do Until ctrl Is Nothing
Yield ctrl
ctrl = source.GetNextControl(ctrl, True)
Loop
End Function
End Module
and then call it in each form as though it were a member.
来源:https://stackoverflow.com/questions/64921636/loop-through-all-checkboxes-on-a-form