Search code examples
c#event-handlinglate-binding

Can I late bind to event handlers in C#?


I'm creating objects dynamically and inserting them into an html table, the objects are either labels or linkbuttons, if they are linkbuttons i need to subscribe an eventhandler to the click event, but I'm struggling to find a way to actually add the handler. The code so far is:

WebControl myControl;

if _createLabel)
{
    myControl = new Label();
}
else
{
    myControl = new LinkButton();
}

myControl.ID = "someID";
myControl.GetType().InvokeMember("Text", BindingFlags.SetProperty, null, myControl,  new object[] { "some text" });

if (!_createLabel)
{
    // somehow do myControl.Click += myControlHandler; here
}

Solution

  • Something like that will work.

    myControl.GetType().GetEvent("Click").AddEventHandler(myControl, myControlHandler);