Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}

1 Answers

The following will work:

LinkButton lnk = myControl as LinkButton;
if (lnk != null)
{
    lnk.Click += myControlHandler;
}
like image 73
Patrick McDonald Avatar answered Dec 10 '25 00:12

Patrick McDonald