Assign event handler to delegate from dynamically added child control

I have a control that handles comments. In this control, I have set up a delegate event handler to send email.

Then I have different types of controls, eg. blog, articles, etc., each of which may or may not contain a comment control (which is executed dynamically with me without knowing the ID), that is, the comment control is added outside of that control. Each of these controls handles emailing it differently (hence the event).

What I am trying to figure out is how to assign an event in the parent control. At the moment, I have to recursively search for all the controls on the page until I find the comment control and set it that way. The example below explains:

COMMENTARY MANAGEMENT

public delegate void Commenting_OnSendEmail();

public partial class Commenting : UserControl
{
   public Commenting_OnSendEmail OnComment_SendEmail();

   private void Page_Load(object sender, EventArgs e)
   {
      if(OnComment_SendEmail != null)
      {
          OnComment_SendEmail();
      }
   }
}

      

PARENT CONTROL

public partial class Blog : UserControl
{
   private void Page_Load(object sender, EventArgs e)
   {
      Commenting comControl = (Commenting)this.FindControl<Commenting>(this);
      if(comControl != null)
      {
         comCtrol.OnComment_SendEmail += new Commenting_OnSendMail(Blog_Comment_OnSendEmail);
      }
   }
}

      

Is there an easier way?

EDIT:

The reason I am asking is because if I search from this. As an initial control, I'm worried about the time it takes to search the control tree to find it. Each different page type will differ in how much control it has. With some testing, it returns a result quickly.

+2


a source to share


1 answer


You can override the AddControl event of your Blog class and check if the added control is of type Commenting. Sort of:

public partial class Blog : UserControl { 

    protected override void AddedControl(Control control, int index) {
      base.AddedControl(control, index);

      Commenting commentingControl = control as Commenting;
      if (commentingControl == null) return;

      commentingControl.OnComment_SendEmail += new Commenting_OnSendMail(Blog_Comment_OnSendEmail);
    }
}

      

Of course, you can put this code in the base class of all your custom control "comments" and have an abstract method to actually handle the event.



Just one thing: the AddControl event happens AFTER Page_Load, so be careful.

Greetings,

Andre

0


a source







All Articles