Flavio Justino Flavio Justino - 2 years ago 68
Vb.net Question

Evaluate expression

So, I have an object with some properties, like this:

Dim.d1, Dim.d2,...,Dim.d50

that return strings. For example:
Dim.d1="Description A", Dim.d2="Description B",etc

What I want to do is to attribute these descriptions to the headers of a Gridview and for that I was thinking using indexes, like this pseudocode:

for i=0 until 49
e.Row.Cells[i].Text = Evaluate(Dim.d(i+1))

So, basically, I need a way to change the call to my object properties depending on the index, but I don't know if it is possible. When
index i=0
, call
, when
index i=1
, and so on until 50.

Any ideas?

Answer Source

You can use methods in the System.Reflection namespace to do this. However, the answer is presented in order to answer the question - you should look at using some of the options suggested by other answerers e.g. use a List(Of String) or something similar.

Anyway, let's say you have a class:

Public Class Class1
    Public Property d1 As String
    Public Property d2 As String
    Public Property d3 As String

End Class

And then, let's say you create an instance of that class and set its properties:

Dim obj As New Class1
obj.d1 = "Foo"
obj.d2 = "Bar"
obj.d3 = "Test"

If you then want to have a loop from 1 to 3, and access e.g. d1, d2, d2 etc then this is where you use Reflection:

For i As Integer = 1 To 3
    Dim info As System.Reflection.PropertyInfo = obj.GetType().GetProperty("d" & i)
    Dim val As String = info.GetValue(obj, Reflection.BindingFlags.GetProperty, Nothing, Nothing, Nothing)

Will give you the output:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download