Anyone experienced with FieldInfo.SetValue

J

jw56578

Im trying to use FieldInfo.SetValue to set the values of fields in a
class, the class is using reflection on itself to popluate its own
fields. but i keep getting this error.

Object type cannot be converted to target type

here is code
Dim myFieldInfo() As System.Reflection.FieldInfo
Dim myType As Type = Me.GetType
' Get the type and fields of FieldInfoClass.
myFieldInfo =
myType.GetFields(Reflection.BindingFlags.NonPublic Or _
Reflection.BindingFlags.Instance Or
Reflection.BindingFlags.Public)

' Display the field information of FieldInfoClass.
Dim i As Integer
For i = 0 To myFieldInfo.Length - 1
Dim customatts() As Object =
myFieldInfo(i).GetCustomAttributes(True)
If customatts.Length > 0 Then
Dim fm As FieldMember = CType(customatts(0),
FieldMember)
If htFields.Contains(fm.DbFieldName) Then
myFieldInfo(i).SetValue(me, htFields(fm.DbFieldName))

End If
Next i

the error occurs on SetValue
 
D

Derek Harmon

Object type cannot be converted to target type : :
If htFields.Contains(fm.DbFieldName) Then
myFieldInfo(i).SetValue(me, htFields(fm.DbFieldName))

It's because the Type retrieved from (Hashtable?) htFields with the
key fm.DbFieldName is not convertible to the Type of the field
whose FieldInfo you're using.

You may need to typecast, using CType( ) or CStr( ) or something,
or the types may just be incompatible (you can't put a String into a
field of type Integer - if the String happens to contain a number you
have to Parse it out manually, as an example).

Look at htFields( fm.DbFieldName).GetType( ) and the type of
the field, and then try to convert between them if possible.


Derek Harmon
 

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