Loop through all Checkboxes on a form [duplicate]

不羁的心 提交于 2020-11-29 23:43:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!