I am having a very hard time subscribing to events in a dynamically loaded user control. It’s probably easiest to just look at the code I am having trouble with. Any help is greatly appreciated.
On the parent page I use this method to dynamically load user controls.
private void LoadMyUserControl(string controlName)
{
parent.Controls.Clear();
// Load the user Control
UserControl MyControl = (UserControl)LoadControl(ControlName);
string userControlID = controlName.Split('.')[0];
MyControl.ID = userControlID.Replace("/","").Replace("~", "");
Type ucType = MyControl.GetType();
// Set misc parameters
PropertyInfo myProp = ucType.GetProperty("MyProp");
myProp.SetValue(MyControl, "MyVal", null);
//Dynamically subscribe to user control event
Type objectType = MyControl.GetType();
EventInfo objectEventInfo = objectType.GetEvent("updateParent");
Type objectEventHandlerType = objectEventInfo.EventHandlerType;
MethodInfo mi = this.GetType().GetMethod("HandledEvent");
Delegate del = Delegate.CreateDelegate(objectEventHandlerType, this, mi);
objectEventInfo.AddEventHandler(this, del);
}
public void HandledEvent (Object sender, EventArgs e)
{
}
My user control has a simple public event like this
public partial class MyUserControl1 : System.Web.UI.UserControl
{
public int MyProp { get; set; }
public event EventHandler updateParent;
}
The error I am getting is on the ObjectEventInfo.AddEventHandler line stating “Object does not match target type.”
Thanks again in advance for your assistance.
Solution #1: Create a common interface.
Solution #2: Create a base class.
Create a base user control class (ie. DynamicUserControlBase for example).
Then in your user control’s you want to dynamically create and subscribe the updateParent event:
Note how it inherits from DynamicUserControlBase. Now, for your LoadMyUserControl method:
However, if you are only working with one type of control you could just as easily change the boxing on LoadControl to:
But it seems as though you are possibly looking at loading many different types of user controls, so the first solution should work fine.
As for your concern via Reflection, try this: