Iterate (loop) through list of variables

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

Hello-

I have numerous variables called varNameX (where X is equal to a
number from 0 to a known number "n").

Using VB.NET, I would like to iterate through all of these variables
to run comparisons.

Example:

For x as Integer = 0 to N
If varName(x).Text = "Some Text" Then
boolFlag = True
End If
Next

Is there a way to "dynamically" iterate through a collection of
variables? If so, what is the suggested way to do this? (An example
would be greatly appreciated).

Steve
 
Hello-

I have numerous variables called varNameX (where X is equal to a
number from 0 to a known number "n").

Using VB.NET, I would like to iterate through all of these variables
to run comparisons.

Example:

For x as Integer = 0 to N
If varName(x).Text = "Some Text" Then
boolFlag = True
End If
Next

Is there a way to "dynamically" iterate through a collection of
variables? If so, what is the suggested way to do this? (An example
would be greatly appreciated).

Steve

Look up the for each loop.

i.e.

Dim varNames As String() = {"one", "two", "three", "four", "five",
"etc"}

For Each name As String In varNames
If name = "three" Then
boolFlag = True
End If
Next

Thanks,

Seth Rowe
 
Hi Steve,

why not using an array?

In case you really need these variables, you should use reflection
for getting/setting their values.

Regards
Bernd
 
Hi Steve,

why not using an array?

In case you really need these variables, you should use reflection
for getting/setting their values.

Regards
Bernd

Bernd is right.

If you feel you need that, double check your program architecture.

Anyway that would be something like (need to add a few checks in real
world programs):

'----------------------------------------

Imports System.Reflection

Public Class Form1

Public Var1 As String = "Name1"
Public Var2 As String = "Name2"
Public Var3 As String = "Name3"
Public Var4 As String = "Name4"
Public Var5 As String = "Name5"

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load

Const Prefix As String = "Var"

For i As Integer = 1 To 5

Dim Flags As BindingFlags = BindingFlags.GetField Or
BindingFlags.Instance Or BindingFlags.Public
Dim f As System.Reflection.FieldInfo =
Me.GetType.GetField(Prefix & i, Flags)
Dim Text As String = f.GetValue(Me)

If Text = "Name3" Then
MsgBox(Text)
End If
Next

End Sub

End Class

'----------------------------------------


Tommaso
 
If the varNameX variables are all controls on a form, then you can just loop
through all the controls and see if the name matches your pattern. If the
order of hitting the controls is important though, then you will need to go
about it another way.
 
Back
Top