views:

472

answers:

4

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
}
A: 

You can simply do:

Control.Event += new EventHandlerType(this.controlClick);

Lloyd
I can't use:myControl.Click += myControlHandler;as WebControl doesn't have a click event so the code won't compile
+2  A: 

Something like that will work.

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

Daniel Brückner
+1  A: 

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));
Marc Gravell
+5  A: 

The following will work:

LinkButton lnk = myControl as LinkButton;
if (lnk != null)
{
    lnk.Click += myControlHandler;
}
Patrick McDonald
+1 for not using reflection.
Marnix van Valen
+1 for you and -1 for me for not seeing the simple solution.
Daniel Brückner