Form docks in Panel only on second try

40 views Asked by At

I am fiddling around with panels to enhance my skills with GUIs :) I found a strange problem and can't find a solution.

I have a form with one button and two panels. In the left panel there is only a button. The right panel should show a form in itself when the button is clicked. The right panels property "dock" is set to "fill" so the right part of the main form is always filled with said panel.

Pic 1

Now I am trying to load a simple form with blue background in the right panel. The form ("TestForm") should always fill the right panel ("TestPanel"). Here is the code:

Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TestPanel.Controls.Clear()
        TestForm.TopLevel = False
        TestForm.Dock = DockStyle.Fill
        TestPanel.Controls.Add(TestForm)
        TestForm.Show()
    End Sub

    Private Sub Form1_Resize(sender As Object, e As EventArgs) Handles Me.Resize
        TestForm.Refresh()
        TestPanel.Refresh()
    End Sub
End Class

What happens is, when I click the button, the form is loaded inside the panel as supposed: Pic 2

But when I resize the main form, the form in the right panel is not filling it up: Pic 3

If I hit the button a second time, it works: Pic 4

I don't understand why I have to click the button a second time.

I fiddled around with the properties of the TestForm and the TestPanel and also tried adjusting the order of loading the TestForm-Control in the TestPanel. But I always ended up having to click the button twice.

1

There are 1 answers

0
HardCode On BEST ANSWER

Don't use the default form instance. Instead, declare an instance of the form Class, just as you would do with any class, and add that to the Panel:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    TestPanel.Controls.Clear()
    TestPanel.Controls.Add(New TestForm)
End Sub

Then, in the constructor of TestForm, assign the Form's properties to allow it to be added to the Panel:

Public Class TestForm

    Public Sub New()
    
        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        TopLevel = False
        Dock = DockStyle.Fill
        Visible = True

    End Sub

End Class