Home > Articles > Programming > Windows Programming

Creating Simple Forms in VB.NET

In this sample chapter, Lowell Mauer focuses on various aspects of creating forms. Button bars or toolbars are essential for most applications designed for Windows these days. Included with these controls are menus that you can add and manipulate within your application.

After you learn how to use these to features to your benefit, you'll learn how to use forms that you've already created as templates for future forms. With this technique, known as inheritance, a new form is created by inheriting the attributes of an existing form.

This sample chapter is excerpted from Sams Teach Yourself More Visual Basic .NET in 21 Days, by Lowell Mauer.
This chapter is from the book

Working with Toolbars

Unless you've been in a closet for the last several years, you should know that almost every Windows application available has one—if not more—toolbar to enhance the user interface. Toolbars enable users to quickly get at an application's commonly used functions. Depending on the application, one or more toolbars could help with specific tasks, such as the Editor Toolbar in the Visual Basic IDE. Because toolbars are so widely used, most users now expect any desktop application they use to have them.

Adding toolbars to your application has become fairly easy with the Toolbar control supplied with Visual Basic. Creating a simple or complicated toolbar requires that you add the following controls to the form:

  • The Toolbar control sets up the buttons of the actual toolbar displayed to users and handles user requests.

  • The ImageList control contains the bitmaps used on the toolbar buttons.

To see how these controls interact to form an application toolbar, start a new project and name it Toolbar.

Adding a Toolbar

Here you see how to use the Toolbar control with the ImageList control. Adding a toolbar is as easy as adding the controls to the form and setting some of their properties. Of course, you still need to add the code to make anything actually happen in the application. The next few sections will discuss the process of creating a toolbar on the form.

Selecting the Images for the Buttons

To create a toolbar, place an ImageList control on your form. To begin the process, add the images you want to use on the toolbar by using the Image Collection Editor (see Figure 3.1). You can display this by clicking the Images button in the ImageList properties list.

Figure 3.1 Using the Image Collection Editor to add images to the ImageList control.

To add an image to the Image collection for the ImageList control, click the Add button. In the Open dialog box that appears, select the image you want to add. When you select the image and click Open, the image is added to the Members list as shown in Figure 3.2.

Find the New and Open bitmaps in /Program Files/ Microsoft Visual Studio.NET/Common7/Graphics/Bitmaps/TLBR_W95 directory and add them to the Image collection. When you're finished, click OK to close the Image Collection Editor.

Figure 3.2 Displaying the images already included in the Image collection.

TIP

Visual Basic installs many different types of graphics files you can use in your applications. You can find any of these files in the /Program Files/Microsoft Visual Studio.NET/Common7/Graphics directory.

To add the toolbar to your project, follow these steps:

  1. Place a Toolbar control on the form. It doesn't really matter where you put it; the default Dock property places it at the top of the form.

  2. Set the ImageList property to the ImageList control you've just added. This property identifies which ImageList control (if you have more than one on the form) the Toolbar control will use to provide the images for the buttons. (Now you can see why you had to set up the ImageList control first.)

Adding the Buttons

The real action starts when you create the buttons for the toolbar. You'll actually add the buttons by using the ToolBarButton Collection Editor (see Figure 3.3).

To add a button to the toolbar, perform the following steps; then if you want to reposition the button, use the up and down arrows to move it to the correct position on the toolbar.

  1. 1. Click the collection button for the Toolbar's Buttons property.

  2. 2. In the ToolBarButton Collection Editor, click Add to add a new button to the toolbar.

  3. 3. Select the image you want on the button by setting the ImageIndex property, using its associated drop-down list (see Figure 3.4).

Figure 3.3 The ToolBarButton Collection Editor allows you to add and modify the buttons and images that you add to the toolbar.

Figure 3.4 Selecting the image to use for a toolbar button.

For each button you add, you will need to specify the following properties:

  • The ItemData property specifies a string that you can use to identify the button in your code. The value of this property must be unique for each button. You should assign a string that's meaningful to you so you can easily remember it when you're writing your code.

  • The ImageIndex property specifies the index of the image you want to appear on the button face. The index corresponds to the index of the picture in the ImageList control. A value of zero for the ImageIndex property will give you a button without an image.

  • The Style property determines the type of button you're creating. The button type also determines how the button will behave in the toolbar. Table 3.1 lists the different Style property settings.

Table 3.1  Setting Button Behavior with the Style Property

Setting

Description

PushButton (default)

Creates a standard push button

Togglebutton

Indicates that an option is on or off

Separator

Provides a space between other buttons

DropDownButton

Displays a drop-down menu list when the button is clicked

Also, you can set several optional properties for each button:

  • Text displays text beneath the image on a button.

  • ToolTipText appears when the mouse is placed on the button. (This text appears only if the ShowTips property of the toolbar is set to True.)

  • Pushed sets or returns the current state of the button.

  • If you set a button style property to DropDownButton, you must set the DropDownMenu property for that button in the ToolBarButton Collection Editor (see Figure 3.5).

Figure 3.5 Setting a menu list on the ToolBarButton Collection Editor.

NOTE

To have a menu to add to the toolbar button, first you must add a ContextMenu control to the form and then set up its menu options. This will be discussed in the next section.

This DropDownMenu feature of the Toolbar offers the functionality included in Visual Basic (see Figure 3.6) and many other Windows-based products.

Figure 3.6 Using drop-down menus from a toolbar.

After you add the buttons to your toolbar, click OK to close the Collection Editor and save the changes. Your form should look like the one in Figure 3.7.

Figure 3.7 The final project form with the Toolbar and ImageList controls set.

Writing the Button Code

You now have a toolbar on your form. If you execute the application, you can click the buttons and see them respond. However, until you add code to the toolbar's events, the buttons won't perform any functions because they don't have any events of their own.

ButtonClick is the toolbar event in which you'll place your button code. This event passes a set of event arguments in an object to the event procedure called e, which allows you to access all the button's properties. In your code, use the value of the ItemData property to determine which button was actually clicked. The following source code is typical for taking actions based on buttons clicked:

Private Sub ToolBar1_ButtonClick(ByVal sender As System.Object,
      ByVal e As System.Windows.Forms.ToolBarButtonClickEventArgs)
      Handles ToolBar1.ButtonClick
    Select Case e.Button.ItemData
        Case "New"
            `ToDo: Add `New' button code.
            MsgBox("Add `New' button code.")
        Case "Open"
            `ToDo: Add `Open' button code.
            MsgBox("Add `Open' button code.")
    End Select
End Sub

TIP

In an actual application, these Case statements should call the same code routine as the related menu options. This allows you to program the action once and then call it from both the menu and the toolbar. Doing this makes it easier to maintain your code because then any changes or corrections have to be made only once.

Notice that each Case statement in the Select statement will execute based on the clicked button. Now your toolbar is ready to have the remaining sections of your application code added.

Other Toolbar Features

One of the newest features to be added to Visual Basic is the ToolTip textbox feature. Almost every object and control in Visual Basic can display ToolTips. Using the toolbar, if you set the ShowTips property to True you can specify unique text for each toolbar button. Text placed in the ToolTipText property for a button is displayed during runtime when the mouse pointer remains on a button for a short period of time (see Figure 3.8).

Figure 3.8 Use ToolTips to inform users what function each button performs.

You're now halfway through the process of creating an easy-to-use form for the application. Save this project—you'll be using it to add the menu in the next section.

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