Search code examples
vb.netformssubform

VB.NET Call Sub of another form


I know, that there are many questions related to this, but still I cannot find a workable solution.

Usually, it would work like this: A form creates an instance of another form in it's container like this:

Dim PolInstIn As New SubForm1

Private Sub LoadDetail()

    PolInstIn.TopLevel = False
    PolInstIn.Name = "Sub From" 
    PolInstIn.FormBorderStyle = Windows.Forms.FormBorderStyle.None
    PolInstIn.Dock = DockStyle.Fill

    Me.GroupBox6.Controls.Add(PolInstIn)
    PolInstIn.Show()

End Sub

Then it's easy to call a Public Sub from the sub form like this:

    Call PolInstIn.MyPublicSubInSubForm1()

However, this doesn't work for me in this case. When I run MyPublicSubInSubForm1() it doesn't throw any error, but does no action. If I write a value to SubForm1 textbox and read it back, it reads, but I don't see it on the screen, so I suspect it is written to some other accidental instance.

I suspect it is because my parent form is also an instance of an form created in very similar way like SubForm1. Basically the ParentForm is a form loaded into tabPage and SubForm1 is a module loaded into ParentForm. It can exist in many copies (tabs).

Could you point to any simple solutions?

Regards,

Libor


Solution

  • I see this question got a lot of views, so here is an answer.

    1) No visual response of child form (only results) - this could have happened if I created more then 1 instances of the form. The example is just an example, but if one use it (accidentally) this way, it may result in new definition of a child form every time (and consequent symptoms like the ones described). In practice, I split form loading from loading data into to the form (done by a public sub in that form).

    2) If you want also a back reference (to i.e. parent grid form), define a Public ParentFormGrid as GridName (note ParentForm is a reserved name) and on loading a child form, set

    PollInstIn.ParentFormGrid = Me
    

    This way you can alway asccess the parent form, i.e. reload the grid when you save changes on a line edited in child form.