Anyone experienced with FieldInfo.SetValue

  • Thread starter Thread starter jw56578
  • Start date Start date
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
 
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
 
Back
Top