Home > Articles > Programming > Windows Programming

  • Print
  • + Share This
This chapter is from the book

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.18Figure 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.

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020