Microsoft KB Archive/821773

= How to switch between forms in a Windows Forms application =

Article ID: 821773

Article Last Modified on 11/26/2007

-

APPLIES TO


 * Microsoft Visual Basic 2005
 * Microsoft Visual Basic .NET 2003 Standard Edition
 * Microsoft Visual Basic .NET 2002 Standard Edition

-





SUMMARY
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.



Switch Between Forms
 Start Microsoft Visual Studio .NET or Microsoft Visual Studio 2005. On the File menu, point to New, and then click Project. 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. Drag a Button control onto Form1. On the Project menu, click Add Windows Form. In the Add New Item dialog box, click Open. Form2 is created. Drag a Button control onto Form2.</li> Right-click Button1, click Properties, and then set both the Name property and the Text property to myButton .</li> In Solution Explorer, double-click Form1 to open the Form1 designer window.</li> Double-click Button1 to open the code window.</li>  Add the following code to the Button1_click event handler in Form1: objForm1.Visible = False objForm2.ShowDialog </li> In Solution Explorer, double-click Form2, and then double-click myButton to open the code window.</li>  Add the following code to the myButton_click event handler in Form2 class: objForm2.Visible = False objForm1.Visible = True </li> On the Project menu, click Add Module. Module1.vb is created.</li>  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 objForm1.ShowDialog End Sub End Module Note Declare variables as Friend because they are accessed from Form1 and Form2 classes. </li> In Solution Explorer, click Project.</li> On the Project menu, click Properties.</li> Set the Startup Object to Sub Main, and then click OK.</li> Build and debug the solution: on the Build menu, click Build Solution. On the Debug menu, click Start. Form1 is displayed.</li> 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.</li> Close either form to quit the application.</li></ol>

<div class="references_section">