Order of Iteration through controls

ZaNi

New member
Joined
Jun 5, 2006
Messages
1
Location
Australia
Programming Experience
3-5
I have been working on a project which needs to accept input from a number of textboxes. In order to minimize redundant code (and because I believe it is good practice), I have written one function that iterates through all the controls, Identifies them by their name, then adds them to the relevant list(there are three lists of textboxes, one list of comboboxes, and one list of labels). This function runs once on startup and sets some global arrays up with all the references they need for the rest of the program.

So far so good, but upon execution, the order is wrong: my first two arrays of textboxes are in the correct order, but the third is in reverse! I have made a small attempt to write a function to reverse the third list (which is not working as of this point), but it seems silly to write a function because the controls are being iterated through in the wrong order...

This leads to my question: Is there a way to alter the order in which controls as iterated through in this loop?

[vbcode]
for each ctl as control in me.controls
'Do stuff with control
next ctl
[/vbcode]

Any information about this would be appreciated.
 
Here is a solution for you using an HashTable Collection. Controls will be sorted according to the TabIndex.
VB.NET:
    Private Sub IndexedControls()
        Dim MyHT As New Hashtable
        Dim Ctl As Control

        For Each Ctl In Me.Controls
            'Add each control to the hashtable collection with the TabIndex as key
            MyHT.Add(Ctl.TabIndex, Ctl)
        Next

        Dim Number As Integer = MyHT.Count 'Number of Controls

        For i As Integer = 0 To Number - 1
            Ctl = CType(MyHT(i), Control)
            'Loop through the collection and retrieve elements with the TabIndex
            Console.WriteLine(i.ToString & vbTab & Ctl.Name)
        Next
    End Sub
 
Back
Top