Displaying Forms from Components
Although most components do not have visual interfaces, there are times when it may be useful for a user to interact visually with a component. For example, a component that represents a bank account might display a specialized alert form when the account is overdrawn. These functions should remain constant in the component and not depend on the client application. Because forms are classes, it is easy to create an instance of the form, and then display it through your component.
There are two approaches you can use to create a form:
- Create the form outside your component, which allows you to use a designer to create the look and feel of the form.
- Make the form a nested class within your component. An advantage to this approach is that the form is always a part of your component, and you have control over how it is used and exposed. The chief disadvantage, however, is that you will be unable to use a designer with your form, and will have to design it all by hand coding.
To display a form from your component
- Create the Windows Form you want to display from your component. For details, see Adding Windows Forms to a Project.
- If the form you want to display is not in the same project as your component, you must create a reference to the project that contains your form by right-clicking References in Solution Explorer and choosing Add Reference. For details, see Adding and Removing References.
- Declare a local variable as a new instance of the form. For example, if your form was called MyForm, your code would look like the following:
' Visual Basic Dim AFormInstance as New MyForm // C# MyForm AFormInstance = new MyForm();
- Call the Show, ShowDialog, and Hide methods of your form to control display, as is shown in the following examples:
' Visual Basic AFormInstance.Show ' Displays the form. AFormInstance.ShowDialog ' Displays the form and waits for user interaction before continuing. AFormInstance.Hide ' Hides the form. // C# // Displays the form. AFormInstance.Show(); // Displays the form and waits for user interaction before continuing. AFormInstance.ShowDialog(); // Hides the form. AFormInstance.Hide();