Quick question regarding event subscription

tempus

Member
Joined
Oct 8, 2013
Messages
11
Programming Experience
10+
I have an event on a winform, call it myEvent. On the winform, I have a some condition that raises that event. So far so good. I have a user control ,myUserControl, that I want to subscribe to the parent form event. Where is the best place to wire this up? I currently have it coded so that it's wired up in the ParentChanged event on the user control. I've read on numerous sites that I should avoid using the Load event of the user control although to be honest, I've never really understood why since all I want to do is wire up a event handler. Which of the two events would be preferred?
 
So you have a control that you want to have react to an event that happens on the form, correct?
What you could do is have a property in your control that holds the handle to the parent form (just set the property = this in the form's load event), then in the property you not only set an internal variable to hold the value but you also add the event call of the parent form's event you're needing to target and point it to your event handling sub.
That will allow you to just drop the control on the form, set the property in the Load event of the form and you're done. When the form's event goes off, so does the control's code.
 
Thanks for the response. Thats essentially what I'm doing now in the ParentChanged event. Here is my ParentChanged event for reference. I was just wondering if the ParentChanged or Load events were the right locations to wire this up.


C#:
private void selectAction_ParentChanged(object sender, EventArgs e)
{
    if (this.Parent != null && this.Parent.GetType() == typeof(MenuPanel))
    {
        MenuPanel myParent = (MenuPanel)this.Parent;
        myParent.ModeToggle -= HandleModeToggle;
        myParent.ModeToggle += HandleModeToggle;        
    }
}
 
Back
Top Bottom