I am trying to handle a button click event of a dynamically loaded usercontrol from my host page. My relevant code is posted below, I think I’m on the right path but what else do I need to make this function properly? I am currently receiveing “Error binding to target method.” when I try to create the usercontrol. Thanks in advance for any assistance!
aspx
<asp:UpdatePanel ID="upLeadComm" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="phComm" runat="server"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
aspx.cs
else if (e.CommandName == "GetComm")
{
string[] cplArg = e.CommandArgument.ToString().Split('§');
UserControl ucLeadComm = (UserControl)LoadControl("Controls/Comments.ascx");
// Set the Usercontrol Type
Type ucType = ucLeadComm.GetType();
// Get access to the property
PropertyInfo ucPropLeadID = ucType.GetProperty("LeadID");
PropertyInfo ucPropLeadType = ucType.GetProperty("LeadType");
EventInfo ucEventInfo = ucType.GetEvent("BtnCommClick");
MethodInfo ucMethInfo = ucType.GetMethod("btnComm_Click");
Delegate handler = Delegate.CreateDelegate(ucEventInfo.EventHandlerType, ucType, ucMethInfo);
ucEventInfo.AddEventHandler(ucType, handler);
// Set the property
ucPropLeadID.SetValue(ucLeadComm, Convert.ToInt32(cplArg[0]), null);
ucPropLeadType.SetValue(ucLeadComm, cplArg[1], null);
phComm.Controls.Add(ucLeadComm);
upLeadComm.Update();
}
ascx.cs
public int LeadID { get; set; }
public string LeadType { get; set; }
public event EventHandler BtnCommClick;
public void btnComm_Click(object sender, EventArgs e)
{
BtnCommClick(sender, e);
}
The problem is that your passing
ucTypewhile you should pass an instance of your UserControl, so try to do:I’m not sure that
ucLeadCommis an istance of the UserControl because I’ve never usedLoadControl(), so if it isn’t use:Activator.CreateInstance();or useGetContructor()andInvoke()it to create an instance of your object.EDIT 1:
Also in that line you should pass an instance of your
UserControlinstead ofucType.EDIT 2:
If I understood in this case you should create the method in your aspx.cs:
And then create another
handlercreating aMethodInfotied tobtnComm_Clickcontained in the aspx.cs and passing it toDelegate.CreateDelegate():