views:

1641

answers:

1

I've some classes defined in a dll file. These are in the form of com api.

I'm trying to create an object of one of the class dynamically and than setting some property of that object.

When I set the property manually, it works, but when I try to invoke the same using reflection it gives the error that

Object does not match target type.

Following is my code

Private Sub SetObjectValue(ByVal SelectedObject As SAPbobsCOM.BoObjectTypes, ByVal ClassName As String, ByVal FieldName As String, ByVal SetValue As String, ByVal KeyValue As String)
    Dim oObject As Object

    Dim myAssembly As Reflection.Assembly = Reflection.Assembly.LoadFrom("interop.sapbobscom.dll")
    Dim myType As Type = myAssembly.GetType(ClassName)

    Dim myMember() As MemberInfo = myType.GetMember(FieldName)
    Dim myProperty As PropertyInfo = CType(myMember(0), PropertyInfo)
    Dim myMethod As MethodInfo = myProperty.GetSetMethod


   oObject = oCompany.GetBusinessObject(SelectedObject)

    oObject.GetByKey(KeyValue)

    myProperty.SetValue(oObject, CDbl(SetValue), Nothing)
End Sub

It gives the error when SetValue method is called. Instead, if I use this like following it works fine:

oObject.CreditLimit = 129
oObject.Update

Where CreditLimit is a property of the given class, and update is a method which I have to call, after the value is set, so that the value in underlying database is updated.

Similarly GetByKey is used to retrieve the value of the object from the underlying database, where the value of the primary key field has to be passed.

Since there are multiple classes and each class has lots of different properties, therefore calling them dynamically will help a lot.

Thanks Rahul Jain

Just tried doing what casper has suggested here. It gives an error saying - Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))

Rahul

Its done. Instead of vbSet, I used vbLet and it completed successfully.

Thanks Rahul

+3  A: 

I am kind of curious why you are doing this, as VB will do all of it for you. You simply have to declare as type object and then make the call, or are you using an option (I believe it is strict?) which prevents you from letting the compiler emit the reflection code for late-bound calls?

If you need to take a parameter, you should be able to use CallByName as well:

Private Sub SetObjectValue(ByVal SelectedObject As SAPbobsCOM.BoObjectTypes, ByVal ClassName As String, ByVal FieldName As String, ByVal SetValue As String, ByVal KeyValue As String)
    Dim oObject As Object
   oObject = oCompany.GetBusinessObject(SelectedObject)

    oObject.GetByKey(KeyValue)

    CallByName(oObject, FieldName, vbSet, CDbl(SetValue))
End Sub
casperOne