Page 1 of 2 12 LastLast
Results 1 to 40 of 46

Thread: Visit Every Control on a Form (includes nested controls, no recursion)

  1. #1

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Visit Every Control on a Form (includes nested controls, no recursion)

    C# version here.

    This code will visit every control on a form, regardless of how deeply it's nested. You could have a TextBox in a Panel in a Splitter in a GroupBox in a TabPage in a TabControl in a Panel and it will still be found. No recursion is needed on your part, as this will simply follow the tab order from start to finish. It also doesn't matter if a control has it's TabStop set to False, as it must still have a TabIndex.
    VB Code:
    1. Dim ctl As Control = Me.GetNextControl(Me, True) 'Get the first control in the tab order.
    2.  
    3. Do Until ctl Is Nothing
    4.     'Use ctl here.
    5.  
    6.     ctl = Me.GetNextControl(ctl, True) 'Get the next control in the tab order.
    7. Loop
    No doubt the GetNextControl method uses recursion internally, but that's not our concern. This will keep your code nice and neat and you'd need a very, very large number of controls before you'd notice a difference in performance.

  2. #2
    Addicted Member
    Join Date
    May 2007
    Posts
    165

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Hey! That's neat!

  3. #3
    Junior Member
    Join Date
    Jul 2007
    Location
    Bergen, Norway
    Posts
    31

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    It seems it might not be able to see controls inside a ToolStripContainer, but I'll report back with further findings.

  4. #4

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    You're correct, because the four ToolStripPanels and the ToolStripContentPanel are accessed via specific properties rather than the Controls collection. I think you'll find that the SplitContainer is in a similar situation.

  5. #5
    Addicted Member
    Join Date
    Sep 2006
    Location
    Surabaya, Indonesia
    Posts
    163

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    jmcilhinney, what about this:

    vb Code:
    1. For Each c As Control In Me.Controls
    2.     'Do something here
    3. Next

    Which is more efficient? I always use this if I want to find any control in my form. But I guess, For each method didn't order by tab control tough ...
    Check my Blog at VB Corner,Component Crafts

  6. #6

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by michaelrawi
    jmcilhinney, what about this:

    vb Code:
    1. For Each c As Control In Me.Controls
    2.     'Do something here
    3. Next

    Which is more efficient? I always use this if I want to find any control in my form. But I guess, For each method didn't order by tab control tough ...
    Your code will visit the controls by z-order as opposed to tab order, but that's by-the-by. The point of my code is that it will visit nested controls too, while yours will only visit those controls parented directly by the form. Your code will not visit any controls that are nested within Panels, GroupBoxes, TabControls, etc.

  7. #7
    Frenzied Member vbdotnetboy's Avatar
    Join Date
    Jun 2004
    Location
    Lewisburg, PA "Next year Raiders in the Super Bowl"
    Posts
    1,310

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    this will definitely come in handy... as always thanks

    Derek - Using VS 2008 99% of the time and VS 2003 1% of the time

    Please Help Us To Save Ana

    ● Helpful Links: DNR TV | Awesome site for tips | Using ADO.NET to work with Excel | Xml Namespace 2.0 Framework Changes|Ultra High Security Password Generator | Mendhak's ADO.NET Tutorial
    ● Code Bank: Random Password Generator | Generic DbProviderFactory Access
    ● Site Work: Bottle Run Xtreme | Spaids Racing.com

    Company I work for - CSSI

    WHEN POSTING PLEASE INDICATE VERSION

    Please use vbcode tags or code tags when posting code
    [highlight=vb]ALL your code goes here[/highlight] or [code]ALL your code goes here[/code]

    If my post helped you in anyway... please be kind and give me some ratings

  8. #8
    Fanatic Member Clanguage's Avatar
    Join Date
    Jan 2008
    Location
    North Carolina
    Posts
    659

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by jmcilhinney
    This code will visit every control on a form, regardless of how deeply it's nested. You could have a TextBox in a Panel in a Splitter in a GroupBox in a TabPage in a TabControl in a Panel and it will still be found. No recursion is need on your part, as this will simply follow the tab order from start to finish. It also doesn't matter if a control has it's TabStop set to False, as it must still have a TabIndex.
    VB Code:
    1. Dim ctl As Control = Me.GetNextControl(Me, True) 'Get the first control in the tab order.
    2.  
    3.         Do Until ctl Is Nothing
    4.             'Use ctl here.
    5.  
    6.             ctl = Me.GetNextControl(ctl, True) 'Get the next control in the tab order.
    7.         Loop
    No doubt the GetNextControl method uses recursion internally, but that's not our concern. This will keep your code nice and neat and you'd need a very, very large number of controls before you'd notice a difference in performance.
    Cool tip jmcilhinney,
    When I think that all this time I have been using nested For Each to retrieve inner controls. Well no more from now on.
    CLanguage;
    IF Post = HelpFull Then
    RateMe
    Else
    Say("Shut UP")
    End If
    DotNet rocks
    VB 6, VB.Net 2003, 2005, 2008, 2010, SQL 2005, WM 5.0,ahem ?OpenRoad?

  9. #9
    Frenzied Member maged's Avatar
    Join Date
    Nov 2002
    Location
    Egypt
    Posts
    1,040

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Greate Piece of code, no more recursive calls


    thx man

  10. #10
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,177

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Very useful. In VS2008 it works for ToolStripContainers too. I have ToolStrips in ToolStripContainers in TabPages in a TabControl on a Form... no problem!

    boops

  11. #11
    New Member
    Join Date
    Oct 2008
    Posts
    3

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    this code can't find Menustrip and Submenus

  12. #12
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    That's because menu's aren't tab-able, even when you set the tab order, the menu's aren't given a number.

  13. #13
    Frenzied Member
    Join Date
    Aug 2006
    Posts
    1,051

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Thanks jm, I used it today.
    Thanks for posting that.

  14. #14
    Lively Member
    Join Date
    Jun 2008
    Posts
    104

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    But what to do if we have to use only some controls???

    it ll do action in all the controls :|

  15. #15

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by hacker786
    But what to do if we have to use only some controls???

    it ll do action in all the controls :|
    My code allows you to visit every control on the form. It does NOT require you to do the something to every one of those controls. There's no reason you can test each control to see if it satisfies come criterion and then only perform your action if it does. You'll notice the word "if" appears in that last sentence a couple of times. That should give you a clue as to how you accomplish this.

  16. #16
    Lively Member
    Join Date
    Jun 2008
    Posts
    104

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    But i want to Reset all textbox from the form.

    When i use this this ll reset all the controls.

    thats u done

    Bt wht i can do for this.

    Blank all the textbox on the form ?

  17. #17
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    33,489

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    So... what's the problem? Inside the loop, check the control's type... if it is a text box, CType it and set its Text property to empty string.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  18. #18

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by hacker786
    But i want to Reset all textbox from the form.

    When i use this this ll reset all the controls.

    thats u done

    Bt wht i can do for this.

    Blank all the textbox on the form ?
    It seems to me that I already told you: only reset the control IF it's a TextBox:
    vb.net Code:
    1. If TypeOf ctl Is TextBox Then
    2.     ctl.ResetText()
    3. End If
    vb.net Code:
    1. Dim txt As TextBox = TryCast(ctl, TextBox)
    2.  
    3. If txt IsNot Nothing Then
    4.     txt.ResetText()
    5. End If

  19. #19
    Lively Member
    Join Date
    Jun 2008
    Posts
    104

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Hmmm Okie

    Thank you i got the clue and i ll done this thanx man

  20. #20
    Hyperactive Member
    Join Date
    Oct 2007
    Posts
    258

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Thanks Jmci! Love it, use it all the time

  21. #21
    New Member
    Join Date
    Aug 2009
    Posts
    2

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Hi,
    I'm trying to use this GetNextControl() function but I'm not sure how to do the declaration or definition for it. I keep getting an error that the method is not found. When I add the following definition:
    Public Function GetNextControl(ctl as Control, forward as boolean) as Control
    It says that I need an "End Function".
    When I try to define it as a Declare statement it gives me an error also.

    What is the correct function declaration I need to be able to use the GetNextControl() method in Visual Basic 6.0??

    I'm trying to mimic the code that is posted at the beggining of this thread.

    By the way I'm doing this because I inheret some visual basic application at work that now I have to maintain. The main form has a ton of controls, some of them hidden. I'm trying to make them all visible so I can see what they look like so I can understand the code. If someone has another way of achieveing this then let me know.

    Thanks in advance for your input :-).

  22. #22
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    33,489

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    don't ... because you can't. Because there isn't an equivalent in VB6... it's new with .NET.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  23. #23
    New Member
    Join Date
    Aug 2009
    Posts
    2

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Well that makes sense. Thanks for the quick response.

    So, any ideas how I can find a hidden control in a VB6 form that I have no idea where it is?

  24. #24
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    33,489

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    nope... not with out thrid party add ons...

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  25. #25
    Addicted Member
    Join Date
    Apr 2009
    Location
    Toronto, Ontario
    Posts
    242

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Shouldn't this work?
    Code:
    for each ctl in me.controls
    ctl.visible = true
    next ctl
    Edited: working from memory, so adapt syntax as needed!
    -EM

  26. #26
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    33,489

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    works at run time... but at designtime, not so much... I think that's what nelg87 was looking for... something to help at design time.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  27. #27
    Hyperactive Member
    Join Date
    Apr 2007
    Posts
    501

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Thanks jmcilhinney , this is useful !
    May I ask a simple question : I noticed you wrote :
    ctl.ResetText
    is it the same as ctl.Text = "" ?

  28. #28
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by iliekater View Post
    Thanks jmcilhinney , this is useful !
    May I ask a simple question : I noticed you wrote :
    ctl.ResetText
    is it the same as ctl.Text = "" ?
    If you place your mouse cursor over the word ResetText the intellesence will popup and tell you about it, or you can highlight commands,methods etc and press F1 to get more help on them.

    F1..MSDN...
    Control.ResetText Method
    Resets the Text property to its default value.

  29. #29
    Hyperactive Member
    Join Date
    Apr 2007
    Posts
    501

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Oh , so this applies to all types of controls ! This could be useful , thanks !

  30. #30
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    5,007

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    I tried this code in a little different fashion

    'Calling Code
    Code:
                        For Each tbp1 As TabPage In tabChannels.Controls
                            For Each ctl1 As Control In tbp1.Controls
                                If TypeOf ctl1 Is TabControl Then
                                    ctl1.Enabled = True
    
                                    For Each tbp2 As TabPage In ctl1.Controls
                                        Select Case tbp2.Name
                                            Case "tabParameter"
                                                EnableDisableControls(tbp2)
                                            Case "tabEquipment"
                                                EnableDisableControls(tbp2)
                                        End Select
                                    Next
                                End If
                            Next
                        Next
    'Called code
    Code:
        Private Sub EnableDisableControls(ByVal c As TabPage)
            Try
                EH.ErrorMessage = String.Empty
    
                Do Until c Is Nothing
                    c = GetNextControl(c, True)
    
                    If TypeOf c Is TextBox Then
                        Dim txt As TextBox = DirectCast(c, TextBox)
                        txt.ReadOnly = True
                    ElseIf TypeOf c Is ComboBox Then
                        Dim cmb As ComboBox = DirectCast(c, ComboBox)
                        cmb.Enabled = False
                    End If
                Loop
    
            Catch ex As Exception
                EH.ErrorMessage = "frmCalibration_3/EnableDisableControls() - " & ex.Message & "...Contact Engineering!" & "~E"
            End Try
        End Sub
    I have a TabControl on my Windows Form. This TabControl contains 8 TabPages with each TabPage containing a UserControl which in turn contains many different controls.

    In my code, I loop through each TabPage of the TabControl. The above routine is called only twice based on the name of the TabPages. As I stepped through the lines of code, it seems to be getting every TabPage within the TabControl rather than every control within the TabPage. Not sure what I'm doing wrong.
    Blake

  31. #31

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    @blakemckenna, the point of this code is to visit every control on a form. It doesn't seem like that is what you actually want. GetNextControl follows the Tab order and is not restricted to a specific container. If what you want is to visit every control on a TabPage then, assuming that all children are on the TabPage directly and not inside other containmers, you should simply loop through the Controls collection of that TablePage.

  32. #32
    PowerPoster
    Join Date
    Jan 2004
    Location
    Southern California
    Posts
    5,007

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    That's what I normally do but your code looked tighter and made more sense! I will go back to what I had.

    Thanks jmc!
    Blake

  33. #33
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    991

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by jmcilhinney View Post
    @blakemckenna, the point of this code is to visit every control on a form. It doesn't seem like that is what you actually want. GetNextControl follows the Tab order and is not restricted to a specific container. If what you want is to visit every control on a TabPage then, assuming that all children are on the TabPage directly and not inside other containmers, you should simply loop through the Controls collection of that TablePage.


    It doesnet work for toolstripmenu items or any non control
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  34. #34

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by coolcurrent4u View Post
    It doesnet work for toolstripmenu items or any non control
    That was basically addressed in post #4, i.e. this code will visit controls that are in a Controls collection of a control that is itself in a Controls collection, etc, all the way up to the form. If there is a break in the control/Controls chain then I don't think that GetNextControl can access it.

  35. #35
    Fanatic Member coolcurrent4u's Avatar
    Join Date
    Apr 2008
    Location
    *****
    Posts
    991

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by jmcilhinney View Post
    That was basically addressed in post #4, i.e. this code will visit controls that are in a Controls collection of a control that is itself in a Controls collection, etc, all the way up to the form. If there is a break in the control/Controls chain then I don't think that GetNextControl can access it.
    Is there any way to make it work for Toostripmenu, Datagridview columns, Toolstripmenuitem and ToolStripbutton?
    because some of these are derived from Component Class
    Programming is all about good logic. Spend more time here


    (Generate pronounceable password) (Generate random number c#) (Filter array with another array)

  36. #36

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by coolcurrent4u View Post
    Is there any way to make it work for Toostripmenu, Datagridview columns, Toolstripmenuitem and ToolStripbutton?
    because some of these are derived from Component Class
    This code relies on the GetNextControl method. That method, as the name suggests, gets the next control. Even then it relies on a direct hierarchy. It's certainly not going to get something that isn't a control. If you want to navigate a menu or a toolbar then you'd have to write code specific to that, which would almost certainly involve recursion..

  37. #37
    New Member
    Join Date
    May 2019
    Posts
    15

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Close Please
    Last edited by vbfailure; Jun 24th, 2019 at 04:02 AM.

  38. #38

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Quote Originally Posted by vbfailure View Post
    Hello,

    I have been looking for something like this, it seems ideal.

    One thing I was curious about, does it actually loop through the controls in the order of the controls TabIndex? During a quick test it seems to loop through everything but in an order not following the TabIndex I have set on various controls.

    Thanks!
    The order of child controls in the parent's Controls collection matches the z-order. You can see this in the designer by using the Document Outline window.

  39. #39
    New Member
    Join Date
    May 2019
    Posts
    15

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    Close Please
    Last edited by vbfailure; Jun 24th, 2019 at 04:02 AM.

  40. #40

    Thread Starter
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    107,648

    Re: Visit Every Control on a Form (includes nested controls, no recursion)

    If you want to visit the controls by TabIndex then simply sort them by TabIndex.
    vb.net Code:
    1. Private Sub ProcessControl(ctrl As Control)
    2.     'Use ctrl here.
    3.  
    4.     For Each child In ctrl.Controls.Cast(Of Control)().OrderBy(Function(c) c.TabIndex)
    5.         'Here be recursion.  Arrrrrrr!
    6.         ProcessControl(child)
    7.     Next
    8. End Sub
    You can kick that off by calling the method and passing the form as an argument. If you don't want to process the form itself then change it to this:
    vb.net Code:
    1. Private Sub ProcessControls(ctrls As Control.ControlCollection)
    2.     For Each child In ctrls.Cast(Of Control)().OrderBy(Function(c) c.TabIndex)
    3.         'Use child here.
    4.  
    5.         'Here be recursion.  Arrrrrrr!
    6.         ProcessControl(child)
    7.     Next
    8. End Sub
    and pass the Controls property of the form to the first call. You can do whatever is appropriate in your specific scenario where it says "Use ctrl here" or "Use child here". Just be aware that sibling controls can have the same TabIndex and that code, as it is, ignores whether TabStop is set to False.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width