Subcribing to a parent event from a child....form / usercontrol...

RE: Windows Forms / User Controls and VB.NET

From within a user control, how can i recieve notification when the control's parent form is closing. I want the notification before anything is disposed so that i can save control states to the registry, namely, the user's last known listview column widths.

I'm thinking of subcribing to the parent form's closing event from within my control, but, then i'll have to add a handler at runtime mapping the form's closing event to it's child control, right  that seems kind of backwards to me....is that good practice  If not, how else can I do what i need to do....

Thanks a lot,

Andy Moyer


Answer this question

Subcribing to a parent event from a child....form / usercontrol...

  • Stuart Carnie

    but i am using a mdi forms....hahahah....that's ok, thanks very much for your for your input. i just saw another article that gave me an idea.....if it works i'll post it soon....

    -Andy Moyer

  • Sander Rijken

    kind of bad design for me too.  in my opinion, controls should be an independent component to any of its parent.  If you want to save the state, that should be the duty of the Form since it is always the mediator for all of the controls in it.  it should always follow the chain of commands, in my opinion, but let's hear others...
  • The Joshinator

    if you dont have an MDI program, you can use Control.TopLevelControl Property

    example (not sure if it works, i didnt test this):

    private withevents ParentForm as system.windows.forms.form

    '''<summary>set ParentForm to the topcontrol (usually a form control)</summary>
    '''<returns>whether the method has succesfully found the parent form.</returns>
    '''<remarks>sometimes you get an error beacause the topcontrol is not (completely) initialised</remarks>
    private function FindParentForm() as boolean
        try
            ParentForm = ctype(me.TopLevelControl , form)
            return true
        catch Ex as exception
            return false
        end try
    end function

    private sub ParentForm_Closing(sender as object, e as canceleventargs) handles ParentForm.Closing
        'Do stuff when form is closing here
    end sub

    if it doesnt work, i'll look again, but i guess this works

    got this from: http://msdn.microsoft.com/library/default.asp url=/library/en-us/cpref/html/frlrfsystemwindowsformscontrolclasstoplevelcontroltopic.asp

    good luck!

  • Subcribing to a parent event from a child....form / usercontrol...