Link to home
Start Free TrialLog in
Avatar of wlawson
wlawson

asked on

Loop through Controls in .NET

You would think this would be the easiest task to do in VB .Net, but the old way of doinf thinsg does not seem to work
And do you reckon I can find it anywhere on the Microsoft Site?

Can someone tell me how I loop through all Textboxes on a Form to simply empty them.
The textboxes are inside a TabPage

Wayne
Avatar of bacon7181
bacon7181

I just recently had to loop through all the controls on a form for something.

This is just one way that you could implement this loop, this uses a recursive function.

    Public Sub DoTheLoop()
        LoopThroughAllControls(Me.Controls)
    End Sub

    Private Sub LoopThroughAllControls(ByVal controls As ControlCollection)
        Dim c As Control
        For Each c In controls
            If GetType(TextBoxBase).IsInstanceOfType(c) Then
                ' c is a textbox based control, do something with it
            End If
            ' loop through sub controls
            LoopThroughAllControls(c.Controls)
        Next
    End Sub
Avatar of wlawson

ASKER

Thanks for that it works well for all Controls on the actual form, but it will not work for anything within the TabPage Control.

Wayne
Avatar of wlawson

ASKER

I can see what your code is trying to do and if feed the TabControl into your Sub Rountine I can count the Controls on the page, but when I try to loop through the controls I get an error "Specific Cast is not valid"
ASKER CERTIFIED SOLUTION
Avatar of bacon7181
bacon7181

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of wlawson

ASKER

Top Shelf ... Worked a treat