vb.net variable name within a variable

 Otherwise know as “variable string to variable” or “How to blow you mind thinking about variables”

Here’s the setup:

3 Variables

 Dim PTCompSalE As Int32 = 0
 Dim PTCompSalX As Int32 = 0
 Dim PTCompSalM As Int32 = 0

Through a series of  Select Case statements I end up with another variable (FullColumnName) that equals the name of one of the above:

Dim FullColumnName As String

Dim beginColumn As String  'PTComp
Dim middleColumn As String  'Sal
Dim endColumn As String  'X

FullColumnName = beginColumn & middleColumn & endColumn   'equals PTCompSalX

The question is, now that I know which variable I want to change values of (PTCompSalX) how do I tell asp.net that I want to change the value of PTCompSalX when the name is actually in another variable?
I could make a Select Case which would work if like in the example I only had 3 options but I have hundreds of options.
After hours of searching I found that Reflection is what I needed, Thanks to shaul_ahuva at Xtreme Visual Basic Talk.

Dim t As Type = Me.GetType()
Dim fi As FieldInfo = t.GetField(FullColumnName) 'get the value of FullColumnName's string reference
fi.SetValue(Me, 1) 'change the value of FullColumnName's string reference

Now PTCompSalX = 1

This allows me to use FullColumnName’s String to find the original variable and change the string for that original variable. Mind Blown!
While Reflection is something new to be, it looks like it will be on my To Read List.

[answer found]

Technorati Tags: , , , ,


Leave a Reply