Search code examples
vb.netinterfaceparent

VB.NET Run sub in parent (instance of) form from a child (instance) of a subform


I know this is very discussed issue, but I didn't find good answers. I have a MainForm containing an instance(s) of Form1 (DataGridView list), which has a subform Form2 (containign details of selected record from Form1). Form1 can have multiple instances (can be loaded into different independent tabs), Form2 can be loaded as independent form into a tab or (and this is the case) into Form1 as detail of selected record.

I can easily refresh the Form2 from Form1 when selecting a record (by defining "Protected f2 As New Form2" I can run subs from Form2). But how do I run a sub in Form1 from Form2? I googled:

  1. Get Parent reference like

    Dim theParentForm1 As Form = TryCast(Me.Owner, Form)
    theParentForm1.MyRefreshSub()
    

    ...this makes sense, because the instances are always paired. But code above doesn't work for me, I cannot access "MyRefreshSub()" from theParentForm1. Perhaps i declared something incorrectly...

  2. Interface - I read a lot of recommendation to use interface, but I didn't find a single example of using interface to refresh a parent form!

Could someone point me toward a solution?

Regards,

Libor


Solution

  • You can do as @Plutonix posted and cast the parent form to Form1 and call the sub

    Dim myParentForm As Form1 = TryCast(Me.Owner, Form1)
    myParentForm.nameOfSubToRun()