views:

286

answers:

1

I have a control that handles commenting. In this control, I have set a delegate event handler for sending an email.

I then have various types of controls, e.g. blog, articles etc, each of which may or may not have the commenting control added (which is done dynamically with me not knowing the id's), i.e. the commenting control is added outside this control. Each of these controls handles it's emailing differently(hence the event).

What I'm trying to determine, is how to assign the event in the parent control. At the moment, I'm having to recursively search through all the controls on the page until I find the comment control, and set it that way. Example below explains:

COMMENTING CONTROL

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 ask is that if I search from this.Page as the initial control, I am worried about time taken to search down the control tree to find it. Each different type of page would be different in how many control it would have. On some testing, it returns back quite quickly the result.

A: 

You could override the AddedControl event of your Blog class and check if the added control is instance of type Commenting. Something like:

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 on a base class of all your "commentable" user controls and have an abstract method to actually handle the event.

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

Cheers,

André

andrecarlucci