Working with Multiple Forms in VB .NET

The previous section described a major change in the forms model from VB6 to VB .NET—the removal of default form instances. This is not a major technical problem; programmers (including VB6 programmers) have been working without default instances of non-form classes for a very long time, but it is a big change if you are used to building Windows applications using VB6. The result of this change is that you need a reference to a particular instance of a form to be able to use it. I will start with a very simple example to illustrate the concept. I will create a new Windows application that contains two forms. Form1, which will be shown automatically when the project runs, will create and display an instance of Form2 when you click a button. To illustrate communication from one form to another, Form2 will also have a button, and it will change the caption of Form1 whenever it is clicked. To get things started, create the new project and add a new form.

Select File, New, Project from the main menu in Visual Studio .NET, and then pick a Visual Basic Windows Application to create. A form will be created with a default name of Form1. Add a second form by right-clicking the project and selecting Add, Add Windows Form from the menu that appears. Accept the default name of Form2 for the new form and click the Open button to finish the wizard.

Creating and Displaying an Instance of a Form

The first step is to add code to Form1 to create and display an instance of Form2. Add a button to Form1, leaving it with a default name of Button1. Now, double-click the button to enter its event procedure for the Click event. If you used the code shown in Listing 3.19, a new form would open every time you click the button, which is likely not the desired result.

Listing 3.19. Simple Code for Displaying a Form
Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles Button1.Click
    Dim myForm As New Form2
    myForm.Show()
End Sub

Instead, you will move the Form variable to a module level value, and then determine if it already exists in the Click event (Listing 3.20). Then, you will create the form if it does not already exist and show it either way.

Listing 3.20. Code That Will Create and Display Only One Copy of a Form
Dim myForm As Form2

Private Sub Button1_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
          Handles Button1.Click
    If myForm Is Nothing Then
        myForm = New Form2
    End If
    myForm.Show()
End Sub

Using the myForm variable allows you to hang on to a reference to your newly created form. Hanging onto the reference returned from creating a new form is useful so that you can talk to this second form if need be. The main reason for using this variable though, is so that you can create and track a single instance of Form2, instead of creating a new one on every button click. Now, let's make Form2 talk back to Form1.

Communicating Between Two Forms

If you want Form2 to be able to communicate with Form1, you need to supply a reference to Form1. Once you do this, you will be set up for two-way communication, as both forms will be holding a reference to the other. The simplest way to accomplish this is to add a public variable (of type Form1) to Form2, like this:

Public Class Form2
    Inherits System.Windows.Forms.Form

    Public myCaller As Form1

Then, right after you create an instance of Form2 in the button click event (see Listing 3.21), you can set this property.

Listing 3.21. You Can Pass a Form Reference with a Property
Dim myForm As Form2

Private Sub Button1_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles Button1.Click
    If myForm Is Nothing Then
        myForm = New Form2
        myForm.myCaller = Me
    End If
    myForm.Show()
End Sub

If code in Form2 needs to access Form1, it can now do so through the myCaller variable. Add a button to Form2 and put this code into it, as shown in Listing 3.22.

Listing 3.22. Now that Form2 Has a Reference to Form1, it Can Access Form1's Properties
Private Sub Button1_Click( _
      ByVal sender As System.Object, _
      ByVal e As System.EventArgs) _
      Handles Button1.Click
    If Not myCaller Is Nothing Then
        myCaller.Text = Now.ToLongTimeString
    End If
End Sub

Clicking the button on Form1 will create an instance of Form2 and populate Form2's myCaller variable with a reference to Form1. Clicking the button on Form2 will access Form1 through the myCaller variable (if it was set) and change its window title. This was a very simple example of communicating between multiple forms, but there will be additional examples as part of the sample applications in Chapters 4 and 5. The next section covers creating and using a form as a dialog box.

Creating and Using a Form as a Dialog Box

Technically speaking, every window/form in an application could be called a dialog box. When I use the term, however, I am referring specifically to a window that is displayed to request some information from the users and return that information back to the application that displayed the dialog box. For the most part, the calling application does not care what happens between displaying the form and the user clicking OK or Cancel to close it; all it is concerned with is the information gathered by the dialog box. To illustrate how you can create a standard dialog box using Visual Basic .NET, this section walks you through the creation of a dialog box that is designed to allow the users to enter in an address (see Figure 3.18).

Figure 3.18. An Address entry dialog box.


Setting Up Your Form

First, you create the sample application and form. Open a new project, a Visual Basic Windows Application, and add a new form named GetAddress. There should now be two forms in your project, which is exactly what you want because we will launch the GetAddress dialog box from Form1. Now, you need to set up the look of GetAddress to match the expected appearance of a dialog box. Set up four text boxes named txtStreet, txtCity, txtPostalCode, and txtCountry on your form and arrange them somewhat like the form shown in Figure 3.18. Now, add two buttons to your form, saveAddress and cancelAddress, with captions of OK and Cancel, respectively. The two buttons should be positioned in the lower-right corner. If you are planning to make your dialog box resizable, you will want to anchor the two buttons to bottom and right. Select the form itself (click any empty area of the design surface) and set its AcceptButton and CancelButton properties to the saveAddress and cancelAddress buttons. Setting these properties allows the users to use the Enter and Escape keys as the equivalent of OK and Cancel. The AcceptButton property also makes the saveAddress button into the default for the form, which causes it to be highlighted. So that you can tell what button was pressed to exit the form, you should also set the DialogResult property of both buttons. Set the DialogResult property for saveAddress to OK, and set it to Cancel for cancelAddress.

If you want your dialog box to be resizable, select the Sizable option for the FormBorderStyle property. For a fixed sized dialog box, you select FixedDialog for FormBorderStyle and set MinimizeBox and MaximizeBox both to False.

Once you have created your dialog box, the key to using it is to determine a method for putting starting data into the dialog box and for pulling out the information the user entered. You could access the various controls (the text boxes) directly, but I strongly advise against it. If you work directly with the controls, you will have to change that code if you ever modify the dialog box. Instead, I suggest one of two approaches. Either create a property procedure for each of the values you are exchanging (street, city, postal code, and country in this example) or create a new class that holds all of these values and then create a single property for that object.

This section shows you both methods; you can use whichever one you prefer. For the first case, using multiple properties, create a property for each of the four values you are dealing with, as shown in Listing 3.23.

Listing 3.23. You Can Insert and Remove Values from Your Dialog Box Using Properties
Public Property Street() As String
    Get
        Return Me.txtStreet.Text
    End Get
    Set(ByVal Value As String)
        Me.txtStreet.Text = Value
    End Set
End Property

Public Property City() As String
    Get
        Return Me.txtCity.Text
    End Get
    Set(ByVal Value As String)
        Me.txtCity.Text = Value
    End Set
End Property

Public Property PostalCode() As String
    Get
        Return Me.txtPostalCode.Text
    End Get
    Set(ByVal Value As String)
        Me.txtPostalCode.Text = Value
    End Set
End Property

Public Property Country() As String
    Get
        Return Me.txtCountry.Text
    End Get
    Set(ByVal Value As String)
        Me.txtCountry.Text = Value
    End Set
End Property
						

For now, these property procedures are just working with the text boxes directly. The value in using property procedures instead of direct control access is that you can change these procedures later, without affecting the code that calls this dialog box. The properties are all set up now, but to make the dialog box work correctly, you also need some code (shown in Listing 3.24) in the OK and Cancel buttons.

Listing 3.24. Don't Forget to Provide a Way to Close Your Forms
Private Sub saveAddress_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles saveAddress.Click
    Me.Close()
End Sub

Private Sub cancelAddress_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles cancelAddress.Click
    Me.Close()
End Sub

Although both button click events do the same thing, close the dialog box, the DialogResult property of each button is set appropriately so it will result in the correct result value being returned to the calling code. In the calling procedure, a button click event on the first form, you populate the dialog box using the property procedures, display it using ShowDialog(), and then retrieve the property settings back into the local variables. ShowDialog is the equivalent of showing a form in VB6 passing in vbModal for the modal parameter, but with the added benefit of a return value. ShowDialog returns a DialogResult value to indicate how the user exited the dialog box. The example in Listing 3.25 checks for the OK result code before retrieving the properties from the dialog box.

Listing 3.25. If Users Click OK, You Must Copy the Values Back, Otherwise You Don't Want to Change Anything Because They Must Have Clicked Cancel
Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click

    Dim address As New addressDialog

    Dim Street As String = "124 First Street"
    Dim City As String = "Redmond"
    Dim Country As String = "USA"
    Dim PostalCode As String = "98052"

    address.Street = Street
    address.City = City
    address.Country = Country
    address.PostalCode = PostalCode

    If address.ShowDialog = DialogResult.OK Then
        Street = address.Street
        City = address.City
        Country = address.Country
        PostalCode = address.PostalCode
    End If
End Sub

The other method I mentioned, using a class to hold a set of values instead of passing each value individually, requires just a few modifications to the code. First, you need to create the class. Add a new class to your project, named Address, and enter the class definition shown in Listing 3.26.

Listing 3.26. With a Class being Used to Hold Multiple Values, You Can Add New Properties to it without Having to Change the Code to Pass it Around
Public Class address
    Dim m_Street As String
    Dim m_City As String
    Dim m_PostalCode As String
    Dim m_Country As String

    Public Property Street() As String
        Get
            Return m_Street
        End Get
        Set(ByVal Value As String)
            m_Street = Value
        End Set
    End Property

    Public Property City() As String
        Get
            Return m_City
        End Get
        Set(ByVal Value As String)
            m_City = Value
        End Set
    End Property

    Public Property PostalCode() As String
        Get
            Return m_PostalCode
        End Get
        Set(ByVal Value As String)
            m_PostalCode = Value
        End Set
    End Property

    Public Property Country() As String
        Get
            Return m_Country
        End Get
        Set(ByVal Value As String)
            m_Country = Value
        End Set
    End Property
End Class
						

This class is nothing more than a convenient way to package data into a single object, but it allows you to have only a single property procedure (Listing 3.27) in the dialog box and to simplify the calling code in Form1 (see Listing 3.28).

Listing 3.27. The Number of Properties Is Reduced to One if You Switch to Using a Class Versus Individual Properties on Your Form
Public Property Address() As address
    Get
        Dim newAddress As New address
        newAddress.City = txtCity.Text
        newAddress.Country = txtCountry.Text
        newAddress.PostalCode = txtPostalCode.Text
        newAddress.Street = txtStreet.Text
        Return newAddress
    End Get
    Set(ByVal Value As address)
        txtCity.Text = Value.City
        txtCountry.Text = Value.Country
        txtPostalCode.Text = Value.PostalCode
        txtStreet.Text = Value.Street
    End Set
End Property
						

Listing 3.28. A Single Property to Exchange Data Simplifies the Calling Code as well as the Form
Private Sub Button1_Click( _
        ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click

    Dim addr As New address
    Dim address As New addressDialog

    Dim Street As String = "124 First Street"
    Dim City As String = "Redmond"
    Dim Country As String = "USA"
    Dim PostalCode As String = "98052"

    addr.Street = Street
    addr.City = City
    addr.Country = Country
    addr.PostalCode = PostalCode

    address.Address = addr
    If address.ShowDialog = DialogResult.OK Then
        addr = address.Address
    End If
End Sub
						

The simple addition of a return code when displaying a modal form makes it easier to implement dialog boxes within Visual Basic .NET, but the lack of default form instances can make all multiple form applications difficult.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.197.183