Only to help you on this problem...
TargetInvocationException means that the method called using Reflection
threw an exception...
You should check the InnerException of the exception raised to have more
details about what happened when you called the method throught
reflection... This is the first step, I guess...
Discover what is the type of "Form.Controls". Is it some specialized
collection?
I would use the following code:
Type formType = formObject.GetType();
PropertyInfo controlCollectionProperty = formType.GetProperty("Controls");
object controlCollection = controlCollectionProperty.GetValue(formObject,
null);
Method addMethod = controlCollectionProperty.PropertyType.GetMethod(" Add");
// If there are overloads, the method signature should be informed here...
addMethod.Invoke(controlCollection, new object[] { your control here }); //
This should work...
But take a look at InnerException property of the exception raised to have
more details about the error.
"Skandy" <sk****************@gmail.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
Hello All:
My second post in as many days! I'm trying to get this working.
I have a form and a user control and trying to add the user control to
this form. Without reflection this would be achieved as
Form.Controls.Add(objUserControl);
Now in my code I have the following:
objUserControl = User Control Object obtained by reflection.
mi is the MethodInfo for the Add method obtained as:
MethodInfo mi = piProp.GetSetMethod();
mi = piProp.PropertyType.GetMethod("Add");
objUserControl.GetType().BaseType returns System.Windows.Forms.Control.
I want to get this working:
mi.Invoke(objForm, new object[] {objUserControl });
But it wouldnt let me as objUserControl causes a
TargetInvocationException. Please let me know how I can handle this.
The end result should be the same as:
Form.Controls.Add(objUserControl);
I know this should be something quite simple, but I'm clearly missing
something and am new to reflection.
Thanks in Advance.
Skanda