How to switch between forms in a Windows Forms application


This step-by-step article describes how to switch between forms in a Windows Forms application.

To display a form, you can use either the Show method or the ShowDialog method. When you use ShowDialog method, the form is displayed as a modal dialog box. Alternatively, you can set the Visible property of the form to True to display a form.

To hide a form, use either the Hide method or the Visible property of the Form.

More Information

Switch Between Forms

  1. Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005.
  2. On the File menu, point to
    New, and then click Project.
  3. Click Visual Basic Projects under
    Project Types, click Windows Application under
    Templates, and then click OK. By default, Form1 is created.

    Note In Visual Studio 2005, click Visual Basic under Project Types.
  4. Drag a Button control onto Form1.
  5. On the Project menu, click Add Windows Form.
  6. In the Add New Item dialog box, click
    Open. Form2 is created.
  7. Drag a Button control onto Form2.
  8. Right-click Button1, click
    Properties, and then set both the Nameproperty and the Text property to myButton.
  9. In Solution Explorer, double-click
    Form1 to open the Form1 designer window.
  10. Double-click Button1 to open the code window.
  11. Add the following code to the Button1_click event handler in Form1:
    objForm1.Visible = False
  12. In Solution Explorer, double-click Form2, and then double-click myButton to open the code window.
  13. Add the following code to the myButton_click event handler in Form2 class:
    objForm2.Visible = False
    objForm1.Visible = True
  14. On the Project menu, click Add Module. Module1.vb is created.
  15. Replace the existing code in Module1.vb with the following code:
    Public Module Module1
    Friend objForm1 As New Form1
    Friend objForm2 As New Form2

    Sub Main()
    End Sub
    End Module
    Note Declare variables as Friend because they are accessed from Form1 and Form2 classes.
  16. In Solution Explorer, click
  17. On the Project menu, click
  18. Set the
    Startup Object to Sub Main, and then click OK.
  19. Build and debug the solution: on the Build menu, click Build Solution. On the Debug menu, click
    Start. Form1 is displayed.
  20. View both forms: on Form1, click Button1. Form1 is hidden, and Form2 is displayed. On Form2, click myButton. Form2 is hidden, and Form1 is displayed again.
  21. Close either form to quit the application.


For more information, visit the following Microsoft Developer Network (MSDN) Web site:

ID do Artigo: 821773 - Última Revisão: 26 de nov de 2007 - Revisão: 1