Cycle throughout all controls

sethindeed

Centurion
Joined
Dec 31, 1969
Messages
118
Location
Montreal Canada
I am looking for a structure that will allow me to cycle to cycle throughout all controls loaded on a form. Something like :

For each ctl in Form
If TypeOf ctl is Combobox Then...

Is it still working in.net ?

thx
 
Visual Basic:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim ctl As Control, s As String
    For Each ctl In Me.Controls
        s = s & vbNewLine & ctl.Name
    Next
    MsgBox("Here is a list of all controls on the form:" & s)
End Sub
Orbity
 
As far as I recall, your code will only return the "top level" controls.
Contents of containers will not be shown, to do so, you'd have to make a recursion into the respective controls collections.
 
Visual Basic:
Public Function NextCycle(ByRef ControlName As Object) As String
Dim Ctl As Control
For Each Ctl In ControlName.Controls
If TypeOf Ctl is Textbox then Ctl.Text = "HELLO"
' If TypeOf Ctl is ......
NextCycle(Ctl)
Next Ctl
End Function

Will Cycle through notice it calls itself, this is for controls such as panels which are containers themselves so it will loop through each container

Call it by

Visual Basic:
NextCycle(Me)

For each control on the form

Hope it Helps

Andy
 
Only diffrence is you have to call itself so container controls such as Panels will have the controls runthrough

Andy
 
Or you can do something like this without recursion:
Visual Basic:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim ctl, ictl As Control, s As String
    For Each ctl In Me.Controls
        s = s & vbNewLine & ctl.Name
        If Not ctl.Controls Is Nothing Then
            For Each ictl In ctl.Controls
                s = s & vbNewLine & "   Child: " & ctl.Name
            Next
        End If
    Next
    MsgBox("Here is a list of all controls on the form:" & s)
End Sub
It seems to work pretty well for me when I tested it.
[edit]actually this will only work for first and second level controls, recursion would be the smoother way to go.[/edit]
Orbity
 
Last edited:
Back
Top