Home All Groups Group Topic Archive Search About

Iterate a structure to get name and value

Author
28 Sep 2006 1:33 PM
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

Author
28 Sep 2006 7:41 PM
Sca_Tone
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
Author
28 Sep 2006 9:24 PM
Chris Dunaway
csgraham74 wrote:
Show quoteHide quote
> 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