Search code examples
c#.netasp.netdelegatesanonymous-methods

How to subscribe to an event dynamically using anonymous methods?


I'm creating a number of UserControls dynamically using LoadControl(String) and want to subscribe to an event of each of them.

All my controls inherits a common Interface that require an implementation of a common Event:

public interface IObjectProcessor
{
    event EventHandler<ObjectProcessedEventArgs> ObjectProcessed;
}

So I do next on my page loading event:

protected void Page_Load()
{
   switch(Request["type"])
   {
     case "user":
     {
        LoadControl("AddUser.ascx", delegate(object sender, ObjectProcessedEventArgs e)
        {
           // do something
        });
        break;
     }
   }
}

private void LoadControl(string path, Action<object, ObjectProcessedEventArgs> action)
{
    var control = (IObjectProcessor)LoadControl(path)
    control.ObjectProcessed // here!
}

How to subscribe a deleagte to this event?


Solution

  • Change Action<object, ObjectProcessedEventArgs> to EventHandler<ObjectProcessedEventArgs>:

    private void LoadControl(string path, EventHandler<ObjectProcessedEventArgs> handler)
    {
            var control = (IObjectProcessor)LoadControl(path)
            control.ObjectProcessed += handler;
    }