Call method dynamically in VB.Net
I have several classes defined in a DLL file. They are in the form com.
I am trying to create an object of one of the classes dynamically and set some property of that object.
When I set the property manually, it works, but when I try to call the same using reflection, it gives an error that
The object does not match the target type.
Below 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 throws an error when calling the SetValue method. Instead, if I use this like after this, it works great:
oObject.CreditLimit = 129 oObject.Update
Where CreditLimit is a property of a given class and update is the method I have to call after the value has been set to update the value in the underlying database.
Similarly, GetByKey is used to retrieve the value of an object from the underlying database, where the value of the primary key field should be passed.
Since there are several classes, and each class has many different properties, so dynamically reversing them helps a lot.
Thank you Rahul Jain
Just tried to do what was suggested here. It gives an error message - Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))
Rahul
Done. Instead of vbSet, I used vbLet and completed successfully.
Thanks Rahul
source to share
I am curious why you are doing this as VB will do everything for you. Do you just have to declare an object of the type and then make the call, or are you using an option (I believe this is strict?) That prevents you from letting the compiler emit reflection code for later calls?
If you need to take a parameter, you can also use CallByName:
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
source to share