Problem with Structures

S

Simang

Hi everyone,

I have a structure with this format:
Public Structure Forms
Public _01234 as string
Public _04321 as string
Public _03456 as integer
End Structure

As you can see, the variable names are all numeric. What I want to do
is that given a numeric string, I have to determine if that string is
a valid variable of the Forms structure and if it is, then output the
value.
For example, the Forms structure has these values:

_01234 = "Test1"
_04321 = "Test2"
_03456 = 100

Lets say I have a function GetStructureValue(varName as string)...
If the varName passed is "01234" then the output of the function
should be "Test1", if 03456, the output is 100, if 98765, which is not
defined in the structure, an error or -1 should be passed.

Is there a way to achieve this in vb.net?

Anyone's help will be much appreciated.

Thanks in advance!

Simang
 
G

Guest

You can do this using reflection (import the System.Reflection namespace).
Your method GetStructureValue might look something like this:

Private Function GetStructureValue(ByVal frm As Forms, ByVal varName As
String) As Object
Dim t As Type = frm.GetType()
Dim field As FieldInfo = t.GetField("_" & varName)
Dim value As Object = field.GetValue(frm)
Return value
End Function

You can call GetStructureValue like this:

Dim frm As New Forms
frm._01234 = "test"
Dim value As Object = GetStructureValue(frm, "01234")
MessageBox.Show(value.ToString())

HTH, Jakob.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top