views:

86

answers:

2

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?

+5  A: 

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

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

HTH, Kent

Kent Boogaart
A: 
control.ObjectProcessed += action
Dewfy
Cannot implicitly convert type 'Action<object,ObjectProcessedEventArgs>' to 'EventHandler<ObjectProcessedEventArgs>'
abatishchev
create explicit declartion of delegate(object sender, ObjectProcessedEventArgs e) and use it as input type
Dewfy