65.9K
CodeProject is changing. Read more.
Home

Non-recursive method to set every control on a form

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.83/5 (8 votes)

Nov 1, 2006

CPOL
viewsIcon

39780

This article discusses a non-recursive method to gain access to every control on a form.

Introduction

Have you ever wanted to easily gain access to every control on a form? This code, though simple, is a way to do just that. In the code provided below, you will see that I used a binary tree traversal method and the Tag property of the controls to change the index of every ComboBox to zero. You can easily modify this code to do whatever you want to each control type.

'Traverse all controls on a form and do something at every node
'(ie. check for ComboBox and set index = 0)
'The tag property of the controls is used to track which nodes have been traversed.

'******************************************************
Dim branchNode As Control = Me      'Current Control
Dim branchLevel As Integer = 0      'Level of branch from top to bottom (ie. most top = 0)
Dim numBranchesOnLevel As Integer = Me.Controls.Count   'Number of branches on current level

While numBranchesOnLevel > 0    'Start at lowest left branch
    branchNode.Tag = 0
    branchNode = branchNode.Controls(branchNode.Tag)
    numBranchesOnLevel = branchNode.Controls.Count
    branchLevel += 1
End While

If branchNode.GetType.ToString = "System.Windows.Forms.ComboBox" Then
'Do this at first node
    Dim theCombo As ComboBox = branchNode
    theCombo.SelectedIndex = 0
End If

For branchLevel = branchLevel To 1 Step -1  'Traverse tree up
    branchNode = branchNode.Parent
    numBranchesOnLevel = branchNode.Controls.Count
    branchNode.Tag += 1
    If Not branchNode.Tag >= numBranchesOnLevel Then
        While numBranchesOnLevel > 0    'Traverse tree right
            branchNode = branchNode.Controls(branchNode.Tag)
            branchNode.Tag = 0
            numBranchesOnLevel = branchNode.Controls.Count
            branchLevel += 1
        End While
    End If
    If branchNode.GetType.ToString = "System.Windows.Forms.ComboBox" Then
    'Do this at every node
        Dim theCombo As ComboBox = branchNode
        theCombo.SelectedIndex = 0
    End If
Next branchLevel
'******************************************************