Iterate a structure to get name and value

  • Thread starter Thread starter csgraham74
  • Start date Start date
C

csgraham74

Hello,

just wondering if someone can help me - im using the following code to
iterate around a structure and get the name of each varaibale in the
structure. Basically i need to get the value of the item in the
structure as well as the name. Would anyone have any ideas on how to go
about this ???

Dim i As Integer
Dim myType As Type = oSAgreements.GetType 'Get the type of
the object
Dim myField As FieldInfo() = myType.GetFields() 'Get the
fields from my() 'type'
For i = 0 To myField.Length - 1
System.Diagnostics.EventLog.WriteEntry("Test Value",
myField(i).name)
Next i

Any help appreciated

Thanks

Colin Graham
 
Hi Colin,
To extract the field name and the value out of the code you posted
you need to amend it as below.

Public Sub TestMe()
Dim oSAgreements As New MyObject
oSAgreements.Field1 = "Value1"
oSAgreements.Field2 = "Value2"

Dim myType As Type = oSAgreements.GetType
For Each myField As Reflection.FieldInfo In myType.GetFields
Console.WriteLine("FieldName: " & myField.Name & " = " &
myField.GetValue(oSAgreements))
Next

End Sub

I'm curious however on what you're developing that would require this
type of code.

Kind Regards,
Tony
 
csgraham74 said:
Hello,

just wondering if someone can help me - im using the following code to
iterate around a structure and get the name of each varaibale in the
structure. Basically i need to get the value of the item in the
structure as well as the name. Would anyone have any ideas on how to go
about this ???

Dim i As Integer
Dim myType As Type = oSAgreements.GetType 'Get the type of
the object
Dim myField As FieldInfo() = myType.GetFields() 'Get the
fields from my() 'type'
For i = 0 To myField.Length - 1
System.Diagnostics.EventLog.WriteEntry("Test Value",
myField(i).name)
Next i

Once you have the FieldInfo for the object, you can call it's GetValue
method. myField(i).GetValue
 
Back
Top