Can I late bind to event handlers in C#?
-
22-08-2019 - |
Question
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);
OTHER TIPS
The following will work:
LinkButton lnk = myControl as LinkButton;
if (lnk != null)
{
lnk.Click += myControlHandler;
}
This shows binding an event on a control (by name) to a method on the current instance (by name):
Button btn = new Button();
EventInfo evt = btn.GetType().GetEvent("Click");
MethodInfo handler = GetType().GetMethod("SomeHandler",
BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
evt.AddEventHandler(btn, Delegate.CreateDelegate(
evt.EventHandlerType, this, handler));
You can simply do:
Control.Event += new EventHandlerType(this.controlClick);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow