Uh-oh, it looks like your Internet Explorer is out of date.

For a better shopping experience, please upgrade now.

Microsoft Visual Basic .NET Step by Step

Microsoft Visual Basic .NET Step by Step

4.6 8
by Michael Halvorson

Here's a fast way for any programmer to begin writing professional Microsoft Windows-based applications for the Microsoft .NET platform-and extend them to the Web-one step at a time. Halvorson shows how to unleash the power of the new, Web-integrated version of Visual Basic, with coverage of object-oriented design strategies and the creation of Web Forms and Web


Here's a fast way for any programmer to begin writing professional Microsoft Windows-based applications for the Microsoft .NET platform-and extend them to the Web-one step at a time. Halvorson shows how to unleash the power of the new, Web-integrated version of Visual Basic, with coverage of object-oriented design strategies and the creation of Web Forms and Web Services.

Product Details

Microsoft Press
Publication date:
Microsoft Step by Step Series
Edition description:
Product dimensions:
7.24(w) x 9.32(h) x 1.69(d)

Read an Excerpt

  • The Basic Use of Controls: The "Hello World" Program
  • Using the DateTimePicker Control
    • The Birthday Program
  • Controls for Gathering Input
    • The Input Controls Demo
    • Looking at the Input Controls Program Code
  • Using the LinkLabel Control
  • One Step Further: Installing ActiveX Controls
    • The Microsoft Chart Control

    Chapter 3   Working with Toolbox Controls

    In this chapter you will learn how to:

    • Use TextBox and Button controls to create a "Hello World" program.
    • Use the DateTimePicker control to display your birth date.
    • Use CheckBox, RadioButton, ListBox, and ComboBox controls to process user input.
    • Use a LinkLabel control to display a Web page on the Internet.
    • Install ActiveX controls.

    As you learned in Chapters 1 and 2, Microsoft Visual Studio .NET controls are the graphical tools you use to build the user interface of a Visual Basic program. Controls are located in the Toolbox in the development environment, and you use them to create objects on a form with a simple series of mouse clicks and dragging motions. Windows Forms controls are specifically designed for building Windows applications, and you'll find them organized on the Windows Forms tab of the Toolbox. (You used a few of these controls in the previous chapter.) You'll learn about other controls, including the tools you use to build Web Forms and database applications, later in the book.

    In this chapter, you'll learn how to display information in a text box, work with date and time information on your system, process user input, and display a Web page within a Visual Basic .NET program. The exercises in this chapter will help you design your own Visual Basic applications and will teach you more about objects, properties, and program code. You'll also learn how to add older ActiveX controls to the Toolbox so that you can extend the functionality of Visual Basic.

    Upgrade Notes: What's New in Visual Basic .NET?
    If you're experienced with Visual Basic 6, you'll notice some new features in Visual Basic .NET, including the following:

    • A new control named DateTimePicker helps you prompt the user for date and time information. The new LinkLabel control is designed to display and manage Web links on a form.
    • The OptionButton control has been replaced with a new RadioButton control.
    • The Frame control has been replaced with a new GroupBox .control.
    • The ListIndex property in the ListBox control has been replaced by a property called SelectedIndex. The same change was made to the ComboBox control.
    • There is no longer an Image control. You use the PictureBox control instead.
    • Images are added to picture box objects using the System.Drawing.Image.FromFile method (not the LoadPicture function).
    • Web browsers and other applications are now started using the System.Diagnostics.Process.Start method.
    • ActiveX controls are added to the Toolbox in a new way and are "wrapped" by Visual Studio so that they can be used in Visual Basic .NET applications.

    The Basic Use of Controls: The "Hello World" Program

    A great tradition in introductory programming books is the "Hello World" program. Hello World is the name given to a short program that demonstrates how the simplest utility can be built and run in a given programming language. In the days of character-based programming, Hello World was usually a two-line or three-line program typed in a program editor and assembled with a stand-alone compiler. With the advent of graphical programming tools, however, the typical Hello World has grown into a complex program containing dozens of lines and requiring several programming tools for its construction. Fortunately, creating a Hello World program is still quite simple with Visual Basic .NET. You can construct a complete user interface by creating two objects, setting two properties, and entering one line of code. Give it a try.

    Create a Hello World program

    1. Start Visual Studio if it isn't already open.
    2. On the File menu, point to New, and then click Project.
    3. Visual Studio displays the New Project dialog box, which prompts you for the name and location of your project and the template that you want to use to open it. (Unlike previous versions of Visual Basic, you begin a project by specifying a name for your program.)

      Use the following instructions each time you want to create a new project on your hard disk.

    4. Make sure the Visual Basic Projects folder is selected, and then click the Windows Application template.
    5. These selections indicate that you'll be building a stand-alone Visual Basic Windows application.

    6. Type MyHello in the Name text box, and then click the Browse button.
    7. The Project Location dialog box opens. You use this dialog box to specify the location of your project and to create new folders for your projects if necessary. Although you can save your projects in any location that you want (the folder \My Documents\Visual Studio Projects is a common location), in this book I will instruct you to save your projects in the c:\vbnetsbs folder, the default location for your Step by Step practice files. If you ever want to remove all of the files associated with this programming course, you will know just where the files are, and you will be able to remove them easily by deleting the entire folder.

      Throughout this book, I ask you to create sample projects with the My prefix, to distinguish your own work from the sample files I include on the companion CD.

    8. Click the Desktop icon in the Project Location dialog box, double-click the My Computer icon, and then browse to the folder c:\vbnetsbs\chap03.
    9. Click the Open button to indicate that the MyHello project and its supporting files will be saved in the c:\vbnetsbs\chap03 folder in a subfolder named MyHello.
    10. The New Project dialog box now looks like this:

      (Image Unavailable)

    11. Click OK to create your new project.
    12. The new project is created and a blank form appears in the Windows Forms Designer, as shown in the following illustration. The two controls you'll use in this exercise, Button and TextBox, are labeled in the Toolbox. If your programming tools are configured differently now, take a few moments to organize them as shown in the illustration. (Chapter 1 describes how to configure the Visual Studio development environment if you need a refresher course.)

      (Image Unavailable)

    13. Click the TextBox control on the Windows Forms tab of the Toolbox.
    14. Draw a text box similar to this:
    15. (Image Unavailable)

      A text box object is used to display text on a form or to get user input while a Visual Basic program is running. How a text box works depends on how you set its properties and how you reference the text box in the program code. In this simple program, a text box object will be used to display the message "Hello, world!" when you click a button object on the form.

      You'll add that button now.

    16. Click the Button control in the Toolbox.
    17. Draw a button below the text box on the form.
    18. Your form should look like this:

      (Image Unavailable)

      A button object is used to get the most basic input from a user. When a user clicks a button, he or she is requesting that the program perform a specific action immediately. In Visual Basic terms, the user is using the button to create an event that needs to be processed in the program. Typical buttons in a program are the OK button, which a user clicks to accept a list of options and indicate that he or she is ready to proceed; the Cancel button, which a user clicks to discard a list of options; and the Quit button, which a user clicks to exit the program. In each case, you should use buttons in a recognizable way so that they work as expected when the user clicks them. A button's characteristics (like those of all objects) can be modified with property settings and references to the object in program code.

    19. Set the following properties for the text box and button objects, using the Properties window. The setting "(empty)" for TextBox1 means that you should delete the current setting and leave the property blank. Settings you need to type in are shown in quotation marks. You shouldn't type the quotation marks.
    20. ObjectPropertySetting

    21. Double-click the OK button, and type the following program statement between the Private Sub Button1_Click and End Sub statements in the Code Editor:
    22. TextBox1.Text = "Hello, world!"

    After you type the TextBox1 object name and a period, Visual Studio displays a list box containing all the valid properties for text box objects, to jog your memory if you've forgotten the complete list. You can select a property from the list by double-clicking it, or you can continue typing and enter it yourself. (I usually just keep on typing, unless I'm exploring new features.)

    The statement you've entered changes the Text property of the text box to "Hello, world!" when the user clicks the button at runtime. (The equal sign assigns everything between the quotation marks to the Text property of the TextBox1 object.) This example changes a property at runtime—one of the most common uses of program code in a Visual Basic program. Your statement is in an event procedure—an instruction that is executed when the Button1 object is clicked. It changes the property setting (and therefore the text box contents) immediately after the user clicks the button.

    Now you're ready to run the Hello World program.

    Run the Hello World program

    1. Click the Start button on the Standard toolbar.
    2. The Hello World program compiles and after a few seconds runs in the Visual Studio development environment.

    3. Click the OK button.
    4. The program displays the greeting "Hello, world!" in the text box, as shown here:

      (Image Unavailable)

      When you clicked the OK button, the program code changed the Text property of the empty TextBox1 text box to "Hello, world!" and displayed this text in the box. If you didn't get this result, repeat the steps in the previous section and build the program again. You might have set a property incorrectly or made a typing mistake in the program code. (Syntax errors appear with a jagged underline in the Code Editor.)

    5. Click the Close button in the upper right corner of the Hello program window to stop the program.

    6. TIP:
      To stop a program running in Visual Studio, you can also click the Stop Debugging button on the Visual Studio Debug toolbar to close the program. (In Visual Basic 6, this button was named End.)

    7. Click the Save All button on the Visual Studio Standard toolbar to save your changes.

    Congratulations—you've joined the ranks of programmers who have written a Hello World program. Now let's try another control.

    Using the DateTimePicker Control

    Some Visual Basic controls display information, and others gather information from the user or process data behind the scenes. In this exercise, you'll work with the DateTimePicker control, which prompts the user for a date or time using a graphical calendar with scroll arrows. Although your use of the control will be rudimentary at this point, experimenting with DateTimePicker will give you an idea of how much Visual Basic controls can do for you automatically and how you process the information that comes from them.

    The Birthday Program

    The Birthday program uses a DateTimePicker control and a Button control to prompt the user for the date of his or her birthday and displays that information using a message box along with other information. Give it a try now.

    Build the Birthday program

    1. On the File menu, click Close Solution to close the MyHello project.
    2. The files associated with the Hello World program are closed.

    3. On the File menu, point to New, and then click Project.
    4. The New Project dialog box appears.

    5. Create a new Visual Basic Windows Application project named MyBirthday in the c:\vbnetsbs\chap03 folder.
    6. The new project is created and a blank form appears in the Windows Forms Designer.

    7. Click the DateTimePicker control in the Toolbox.

    8. TIP:
      If you don't see the DateTimePicker in the Toolbox, it may be lower in the Toolbox list hidden from your view. To scroll down in the Toolbox list, click the down scroll arrow next to the Clipboard Ring tab. To scroll back up, click the up scroll arrow next to the Windows Forms tab.

    9. Draw a date time picker object in the middle of the form, as shown in the following:
    10. (Image Unavailable)

      The date time picker object by default displays the current date, but you can adjust the date displayed by changing the object's Value property. Displaying the date is a handy design guide—it lets you size the date time picker object correctly when you are creating it.

    11. Click the Button control in the Toolbox, and then add a button object below the date time picker.
    12. You'll use this button to display your birth date and verify that the date time picker works correctly.

    13. In the Properties window, change the Text property of the button object to Show My Birthday.
    14. Now you'll add a few lines of program code to a procedure associated with the button object. This procedure is called an event procedure because it runs when an event, such as a mouse click, occurs in the object.

    15. Double-click the button object on the form, and then type the following program statement between the Private Sub and End Sub statements in the Button1_Click event procedure:
    16. MsgBox("Your birth date was " & DateTimePicker1.Text)
      MsgBox("Day of the year: " & _ 
      MsgBox("Today is " & DateTimePicker1.Value.Now.ToString())

      These program statements display three successive message boxes (small dialog boxes) with information from the date time picker object. The first line uses the Text property of the date time picker to display the birth date information you select when using the object at runtime. The MsgBox function displays the string value "Your birth date was" in addition to the textual value held in the date time picker's Text property. These two pieces of information are joined together by the string concatenation operator (&). You'll learn more about the MsgBox function and the string concatenation operator in Chapter 5.

      The second and third lines collectively form one program statement and have been broken by the line continuation character (_) because the statement was a bit too long to print in our book. (See Tip box below for an explanation of this useful convention for breaking longer lines.) The statement DateTimePicker1.Value.DayOfYear.ToString() uses the date time picker object to calculate the day of the year in which you were born, counting from January 1. This is accomplished by the DayOfYear property and the ToString method, which converts the numeric result of the date calculation to a textual value that is more easily displayed by the MsgBox function.

      Methods are special statements that perform an action or a service for a particular object, such as converting a number to a string or adding items to a list box. Methods differ from properties, which contain a value, and event procedures, which execute when a user manipulates an object. Methods can also be shared among objects, so when you learn how to use one method, you'll often be able to apply it to several circumstances. We'll discuss several important methods as you work through this book.

      The fourth line in the program code uses the Now property to check your computer's system clock for the current date and time and displays that information in a message box after converting it to a string, or textual, value.

      Program lines can be more than 65,000 characters long in the Visual Studio Code Editor, but it is usually easiest to work with lines of 80 or fewer characters. You can divide long program statements among multiple lines by using a space and a line continuation character (_) at the end of each line in the statement, except the last line. (You cannot use a line continuation character to break a string that is in quotation marks, however.) I use the line continuation character in this exercise to break the second line of code into two parts.

      After you enter the code for the Button1_Click event procedure, the Code Editor should look similar to the following illustration.

      (Image Unavailable)

    17. Click the Save All button to save your changes to disk.

    Now you're ready to run the Birthday program.

    Run the Birthday program

    1. Click the Start button on the Standard toolbar.
    2. The Birthday program starts to run in the development environment. The current date is displayed in the date time picker.

    3. Click the drop-down arrow in the date time picker to display the object in calendar view.
    4. Your form will look like the illustration on the following page. (You'll see a different date.)

      (Image Unavailable)

    5. Click the left scroll arrow to look at previous months on the calendar.
    6. Notice that the text box portion of the object also changes as you scroll the date. The "today" value at the bottom of the calendar doesn't change, however.

      Although you could scroll all the way back to your exact birthday, you may not have the patience to scroll month by month. To move to your birth year faster, select the year value in the date time picker text box and enter a new date.

    7. Select the four-digit year in the date time picker text box.
    8. When you select the date, the date time picker will close.

    9. Type your birth year in place of the year that is currently selected, and then click the drop-down arrow again.
    10. The calendar reappears in the year of your birth.

    11. Click the scroll arrows again to locate the month in which you were born, and then click the exact day on which you were born.
    12. If you didn't know the day of the week you were born on, now you can find out!

      When you select the final date, the date time picker closes, and your birth date is displayed in the text box. Now click the button object to see how this information is made available to other objects on your form.

    13. Click the Show My Birthday button.
    14. Visual Basic executes your program code and displays a message box containing the day and date of your birth. Notice how the two dates match:

      (Image Unavailable)

    15. Click OK in the message box.
    16. A second message box appears indicating which day of the year you were born on.

    17. Click OK to display the final message box.
    18. The current date and time are displayed—the program works!

      You'll find the date time picker object to be quite capable—not only does it remember the new date or time information that you enter, but it keeps track of the current date and time as well, and it can display this date and time information in a variety of useful formats.

      To configure the date time picker object to display times instead of dates, set the object's Format property to Time.

    19. Click OK to close the message box, and then click the Close button on the form.
    20. You're finished using the DateTimePicker control for now.

    A Word About Terminology

    So far in this book I've used several different terms to describe items in a Visual Basic program. Although I haven't defined each of them formally, it's worth listing several of them now to clear up any confusion. Can you tell the difference yet?

    Program statement  A program statement is a keyword in the code that does the work of the program. Visual Basic program statements create storage space for data, open files, perform calculations, and do several other important tasks. Most keywords are shown in blue type in the Code Editor.

    Variable  A variable is a special container used to hold data temporarily in a program. The programmer creates variables using the Dim statement to store the results of a calculation, create filenames, process input, and so on. Numbers, names, and property values can be stored in variables.

    Control  A control is a tool you use to create objects on a Visual Basic form. You select controls from the Toolbox and use them to draw objects on a form with the mouse. You use most controls to create user interface elements, such as buttons, picture boxes, and list boxes.

    Object  An object is the name of a user interface element you create on a Visual Basic form with a Toolbox control. You can move, resize, and customize objects by using property settings. Objects have what is known as inherent functionality—they know how to operate and can respond to certain situations on their own. (A list box "knows" how to scroll, for example.) And objects are the members of classes, which serve as the blueprints for defining what an object does. You can program Visual Basic objects by using customized event procedures for different situations in a program. In Visual Basic, the form itself is also an object.

    Property  A property is a value, or characteristic, held by an object. For example, a button object has a Text property to specify the text that appears on the button and an Image property to specify the path to an image file that should appear on the button face. In Visual Basic, properties can be

    set at design time by using the Properties window or at runtime by using statements in the program code. In code, the format for setting a property is

    Object.Property = Value

    where Object is the name of the object you're customizing, Property is the characteristic you want to change, and Value is the new property setting. For example,

    Button1.Text = "Hello"

    could be used in the program code to set the Text property of the Button1 object to "Hello".

    Event procedure  An event procedure is a block of code that is executed when an object is manipulated in a program. For example, when the Button1 object is clicked, the Button1_Click event procedure is executed. Event procedures typically evaluate and set properties and use other program statements to perform the work of the program.

    Method  A method is a special statement that performs an action or a service for a particular object in a program. In program code, the notation for using a method is


    where Object is the name of the object you want to work with, Method is the action you want to perform, and Value is an optional argument to be used by the method. For example, the statement


    uses the Add method to put the word Check in the ListBox1 list box. Methods and properties are often identified by their position in a collection or object library, so don't be surprised if you see very long references such as System.Drawing.Image.FromFile, which would be read as "the FromFile method, which is a member of the Image class, which is a member of the System.Drawing object library (or namespace)."

    Controls for Gathering Input

    Visual Basic provides several mechanisms for gathering input in a program. Text boxes accept typed input, menus present commands that can be clicked or chosen with the keyboard, and dialog boxes offer a variety of elements that can be chosen individually or selected in a group. In this exercise, you'll learn to use four important controls that will help you gather input in several different situations. You'll learn about the RadioButton, CheckBox, ListBox, and ComboBox controls. You will explore each of these objects as you use a Visual Basic program called Input Controls, the user interface for a graphical ordering system. As you run the program, you'll get some hands-on experience with the input objects. In the next chapter, I'll discuss how these objects can be used along with menus in a full-fledged program.

    As a simple experiment, try using the CheckBox control now to see how user input is processed on a form and in program code. Follow these steps:

    Experiment with the CheckBox control

    1. On the File menu, click Close Solution to close the Birthday project.
    2. On the File menu, point to New, and then click Project.
    3. The New Project dialog box appears.

    4. Create a new Visual Basic Windows Application project named MyCheckBox in the c:\vbnetsbs\chap03 folder.
    5. The new project is created and a blank form appears in the Windows Forms Designer.

    6. Click the CheckBox control in the Toolbox.
    7. Draw two check box objects on the form, one above the other.
    8. Check boxes appear like objects on your form just as other objects do.

    9. Click the PictureBox control and draw two square picture box objects beneath the two check boxes.
    10. Set the following properties for the check box and label objects:
    11. ObjectPropertySetting
      CheckBox1Checked TextTrue "Calculator"
      CheckBox2Text"Copy machine"
      PictureBox1Image SizeModec:\vbnetsbs\chap03\calcultr.bmp StretchImage

      In this demonstration program, you'll use the check boxes to display and hide images of a calculator and a copy machine. The Text property of the check box object determines the contents of the check box label in the user interface. The Checked property lets you set a default value for the check box. Setting Checked to True will place a check mark in the box, and setting Checked to False (the default setting) will remove the check mark. I use the SizeMode properties in the picture boxes to size the images so that they stretch to fit in the picture box.

      Your form should look like this:

      (Image Unavailable)

    12. Double-click the first check box object to open the Code Editor for the CheckBox1_CheckedChanged event procedure, and then enter the following program code:
    13. If CheckBox1.CheckState = 1 Then
          PictureBox1.Image = System.Drawing.Image.FromFile _
          PictureBox1.Visible = True
          PictureBox1.Visible = False
      End If

      The CheckBox1_CheckChanged event procedure runs only if the user clicks in the first check box object. The event procedure uses an If…Then decision structure (described in Chapter 6) to check the current status, or "state," of the first check box, and it displays a calculator picture from the c:\vbnetsbs\chap03 folder if a check mark is in the box. The CheckState property holds a value of 1 if there is a check mark present and 0 if there is no check mark present. I use the Visible property to display the picture if a check mark is present or hide the picture if a check mark isn't present. .Notice that I wrapped the long line that loads the image into the picture box object by using the line continuation (_) character.

    14. Click the View Designer button in Solution Explorer to display the form again, and then double-click the second check box and add the following code to the CheckBox2_CheckedChanged event procedure:
    15. If CheckBox2.CheckState = 1 Then
          PictureBox2.Image = System.Drawing.Image.FromFile _
          PictureBox2.Visible = True
          PictureBox2.Visible = False
      End If

      This event procedure is almost identical to the one that you just entered; only the names of the image (copymach.bmp), the check box object (CheckBox2), and the picture box object (PictureBox2) are different.

    16. Click the Save All button on the Standard toolbar to save your changes.

    Run the CheckBox program

    1. Click the Start button on the Standard toolbar.
    2. Visual Basic runs the program in the development environment. Because you placed a check mark in the first check box, the calculator image appears on the form.

    3. Click the Copy machine check box.
    4. Visual Basic displays the copy machine image, as shown here:

      (Image Unavailable)

    5. Experiment with different combinations of check boxes, clicking the boxes several times to test the program. The program logic you added with a few short lines of Visual Basic code manages the boxes perfectly. (You'll learn much more about program code in upcoming chapters.)
    6. Click the Close button on the form to end the program.

    The Input Controls Demo

    Now that you've had a little experience with check boxes, run and examine the Input Controls demonstration program that I created to simulate an electronic ordering environment that makes more extensive use of check boxes, radio buttons, a list box, and a combo box. If you work in a business that does a lot of order entry, you might want to expand this into a full-featured graphical order entry program. After you experiment with Input Controls, spend some time learning how the four input controls work in the program. They were created in a few short steps by using Visual Basic and the techniques you just learned.

    Run the Input Controls program

    1. On the File menu, point to Open, and then click Project.
    2. The Open Project dialog box appears.

    3. Open the c:\vbnetsbs\chap03\input controls folder, and then double-click the Input Controls project file (Input Controls.vbproj).
    4. The Input Controls project opens in the development environment.

    5. If the project's form isn't visible, click the Form1.vb form in Solution Explorer and then click the View Designer button.
    6. Move or close the windows that block your view of the form so that you can see how the objects are laid out.
    7. You'll see a form similar to this:

      (Image Unavailable)

      The Input Controls form contains radio button, check box, list box, combo box, picture box, button, and label objects. These objects work together to create a simple order entry program that demonstrates how the Visual Basic input objects work. When the Input Controls program is run, it loads images from the \vbnetsbs\chap03\input controls folder on drive C and displays them in the six picture boxes on the form.

      If you installed the practice files in a location other than the default c:\vbnetsbs folder, the statements in the program that load the artwork from the disk will contain an incorrect path. (Each statement begins with c:\vbnetsbs\chap03\input controls, as you'll see soon.) If this is the case, you can make the program work by renaming your practice files folder \vbnetsbs or by changing the paths in the Code Editor using the editing keys or the Find And Replace submenu on the Edit menu.

    8. Click the Start button on the Standard toolbar.
    9. The program runs in the development environment.

    10. Click the Laptop radio button in the Computer box.
    11. The image of a laptop computer appears in the Products Ordered area on the right side of the form. The user can click various options and the current choice is depicted in the order area on the right. In the Computer box, a group of radio buttons is used to gather input from the user. (Note: Radio buttons were called option buttons in Visual Basic 6.) Radio buttons force the user to choose one (and only one) item from a list of possibilities.

      When radio buttons are placed inside a group box object on a form, the radio buttons are considered to be part of a group and only one option can be chosen. To create a group box, click the GroupBox control on the Windows Forms tab of the Toolbox, and then draw the control on your form. (The GroupBox control replaces the Frame control in Visual Basic 6.) You can give the group of radio buttons a title (as I have) by setting the Text property of the group box object. When you move a group box object on the form, the controls within it also move.

    12. Click the Answering Machine, Calculator, and Copy Machine check boxes in the Office Equipment box.
    13. Check boxes are used in a program so that the user can select more than one option at a time from a list. Click the Calculator check box again, and notice that the picture of the calculator disappears from the order area. Because each user interface element is live and responds to click events as they occur, order choices are reflected immediately. The code that completes these tasks is nearly identical to the code you entered earlier in the CheckBox program.

    14. Click Satellite Dish in the Peripherals list box.
    15. A picture of a satellite dish is added to the order area. A list box is used to get a user's single response from a list of choices. List boxes are created with the ListBox control, and may contain many items to choose from (scroll bars appear if the list of items is longer than the list box). Unlike radio buttons, a default selection isn't required in a list box. In a Visual Basic program, items can be added to, removed from, or sorted in a list box while the program is running. If you would like to see check marks next to the items in your list box, use the CheckedListBox control in the Toolbox instead of the ListBox control.

    16. Now choose U.S. Dollars (sorry, no credit) from the payment list in the Payment Method combo box.
    17. A combo box, or drop-down list box, is similar to a regular list box, but it takes up less space. (The "combo" in a combo box basically comes from a "combination" of an editable text box and a drop-down list.) Visual Basic automatically handles the opening, closing, and scrolling of the list box. All you do as a programmer is create the combo box using the ComboBox control in the Toolbox, set the Text property to provide directions or a default value, and then write code to add items to the combo box and to process the user's combo box selection. You'll see examples of each task in the program code for the Input Controls demonstration.

      After you make your order selections, your screen should look something like this:

      (Image Unavailable)

    18. Practice making a few more changes to the order list in the program (try different computers, peripherals, and payment methods), and then click the Quit button in the program to exit.
    19. The program closes when you click Quit, and the programming environment appears.

    Looking at the Input Controls Program Code

    Although you haven't had much formal experience with program code yet, it's worth taking a quick look at a few event procedures in Input Controls to see how the program processes input from the user interface elements. In these procedures, you'll see the If…Then and Select Case statements at work. You'll learn about these and other decision structures in Chapter 6. For now, concentrate on the CheckState property, which changes when a check box is selected, and the SelectedIndex property, which changes when a list box is selected.

    Examine the check box code and the list box code

    1. Be sure the program has stopped running, and then double-click the Answering Machine check box in the Office Equipment box to display the CheckBox1_CheckedChanged event procedure in the Code Editor.
    2. You'll see the following program code:

      ‘If the CheckState property for a check box is 1, it has a mark in it
      If CheckBox1.CheckState = 1 Then
          PictureBox2.Image = System.Drawing.Image.FromFile _
            ("c:\vbnetsbs\chap03\input controls\answmach.bmp")
          PictureBox2.Visible = True
          ‘If there is no mark, hide the image
          PictureBox2.Visible = False
      End If

      The first line of this event procedure is called a comment. Comments are displayed in green type and are simply notes written by the programmer to describe what is important or interesting about this particular piece of program code. (Comments are also occasionally generated by automated programming tools that compile programs or insert code snippets.) I wrote this comment to remind myself that the CheckState property contains a crucial value in this routine—a value of 1 if the first check box was checked.

      The rest of the event procedure is nearly identical to the one you just wrote in the CheckBox program. If you scroll down in the Code Editor, you'll see a similar event procedure for the CheckBox2 and CheckBox3 objects.

    3. At the top edge of the Code Editor, click the tab labeled "Form1.vb [Design]" to display the form again, and then double-click the Peripherals list box on the form.
    4. The ListBox1_SelectedIndexChanged event procedure appears in the Code Editor. You'll see the following program statements:

      ‘The item you picked (0-2) is held in the SelectedIndex property
      Select Case ListBox1.SelectedIndex
          Case 0
              PictureBox3.Image = System.Drawing.Image.FromFile _
                ("c:\vbnetsbs\chap03\input controls\harddisk.bmp")
          Case 1
              PictureBox3.Image = System.Drawing.Image.FromFile _
                ("c:\vbnetsbs\chap03\input controls\printer.bmp")
          Case 2
              PictureBox3.Image = System.Drawing.Image.FromFile _
                ("c:\vbnetsbs\chap03\input controls\satedish.bmp")
      End Select

      Here you see code that executes when the user clicks an item in the Peripherals list box in the program. In this case, the important keyword is ListBox1.SelectedIndex, which is read "the SelectedIndex property of the first list box object." After the user clicks an item in the list box, the SelectedIndex property returns a number that corresponds to the location of the item in the list box. (The first item is numbered 0, the second item is numbered 1, and so on.)

      In the previous code, SelectedIndex is evaluated by the Select Case decision structure, and a different image is loaded depending on the value of the SelectedIndex property. If the value is 0, a picture of a hard disk is loaded; if the value is 1, a picture of a printer is loaded; if the value is 2, a picture of a satellite dish is loaded. You'll learn more about how the Select Case decision structure works in Chapter 6.

    5. At the top edge of the Code Editor, click the Form1.vb [Design] tab to display the form again, and then double-click the form (not any of the objects) to display the code associated with the form itself.
    6. The Form1_Load event procedure appears in the Code Editor. This is the procedure that is executed each time the Input Controls program starts, or loads. Programmers put program statements in this special procedure when they want them executed every time a form loads. (Your program can display more than one form, or none at all, but the default behavior is that Visual Basic loads and runs the Form1_Load event procedure each time the user runs the program.) Often, as in the Input Controls program, these statements define an aspect of the user interface that couldn't be created by using Toolbox controls or the Properties window.

      Here is what the Form1_Load event procedure looks like for this program:

      ‘These program statements run when the form loads
      PictureBox1.Image = System.Drawing.Image.FromFile _
        ("c:\vbnetsbs\chap03\input controls\pcomputr.bmp")
      ‘Add items to a list box like this:
      ListBox1.Items.Add("Extra hard disk")
      ListBox1.Items.Add("Satellite dish")
      ‘Combo boxes are also filled with the Add method:
      ComboBox1.Items.Add("U.S. Dollars")
      ComboBox1.Items.Add("English Pounds")

      Three lines in this event procedure are comments displayed in green type. The second line in the event procedure loads the personal computer image into the first picture box. (This line is broken in two using a space and the line continuation character, but the compiler still thinks of it as one line.) Loading an image establishes the default setting reflected in the Computer radio button group box. The next three lines add items to the Peripherals list box (ListBox1) in the program. The words in quotes will appear in the list box when it appears on the form. Below the list box program statements, the items in the Payment Method combo box (ComboBox1) are specified. The important keyword in both these groups is Add, which is a special function, or method, to add items to list box and combo box objects.

    You're finished using the Input Controls program. Take a few minutes to examine any other parts of the program you're interested in, and then move on to the next exercise.

    Using the LinkLabel Control

    Providing access to the Web is now a standard feature of many Windows applications, and Visual Studio .NET makes adding this functionality easier than ever before. You can create sophisticated Web-aware applications using Web Forms and other technologies in Visual Studio, or you can open a simple Web page using your computer's Web browser using just a few lines of program code.

    In this exercise, you'll learn to use the LinkLabel control to display text on a Visual Basic form that looks and acts just like an Internet link. The LinkLabel control is a new addition to Visual Basic, and when you combine it with the Process.Start method, you can quickly open links on your form using Internet Explorer, Netscape Navigator, or another browser. Use the LinkLabel control now to connect to the Microsoft Press home page on the Internet.

    To learn more about writing Web-aware Visual Basic .NET applications, read Chapters 21-22.

    Create the WebLink program

    1. On the File menu, click Close Solution to close the Input Controls project.
    2. On the File menu, point to New, and then click Project.
    3. The New Project dialog box appears.

    4. Create a new Visual Basic Windows Application project named MyWebLink in the c:\vbnetsbs\chap03 folder.
    5. The new project is created and a blank form appears in the Windows Forms Designer.

    6. Click the LinkLabel control in the Toolbox, and draw a rectangular link label object on your form.
    7. Link label objects look like label objects, except that all label text is displayed in blue underlined type on the form.

    8. Set the Text property of the link label object to www.microsoft.com/mspress/ (the Web site for Microsoft Press).
    9. Your form will look like this:

      (Image Unavailable)

    10. Click the form in the development environment to select it. (The form itself, not the link label object.)
    11. This is the technique you use to view the properties of the default form or Form1 in the Properties window. Like other objects in your project, the form also has properties that you can set.

    12. Set the Text property of the form object to Web Link Test.
    13. The Text property for a form controls what appears on the form's title bar when the program runs. Although this isn't customization related exclusively to the Web, I thought you'd enjoy picking up that skill now, before we move on to other projects. (We'll customize the title bar in most of the programs we build.)

    14. Double-click the link label object, and type the following program code in the LinkLabel1_LinkClicked event procedure:
    15. ‘ Change the color of the link by setting LinkVisited to True.
      LinkLabel1.LinkVisited = True
      ‘ Use the Process.Start method to open the default browser 
      ‘ using the Microsoft Press URL:
      System.Diagnostics.Process.Start _

      I've included comments in the program code to give you some practice entering them. As soon as you enter the single quote character (‘), Visual Studio changes the color of the line to green, identifying the line as a comment. Comments are for documentation purposes only—they aren't evaluated or executed by the compiler.

      The two program statements that aren't comments actually control how the link works. Setting the LinkVisited property to True gives the link that dimmer color of purple which indicates in many browsers that the HTML document associated with the link has already been viewed. Although setting this property isn't necessary to display a Web page, it is good programming practice to provide the user with information that is consistent in other applications.

      The second program statement (that was broken into two lines) runs the default Web browser (such as Internet Explorer) if the browser isn't already running. (If the browser is running, the URL just loads immediately.) The Start method in the Process class performs the important work, by starting a process or executable program session in memory for the browser. The Process class, which manages many other aspects of program execution, is a member of the System.Diagnostics object library, which Visual Basic .NET programmers called the System.Diagnostics namespace. By including an Internet address or URL along with the Start method, I'm letting Visual Basic know that I want to view a Web site, and Visual Basic is clever enough to know that the default system browser is the tool that would best display that URL, even though we didn't identify the browser by name.

      An exciting feature of the Process.Start method is that it can be used to run other Windows applications, too. If I did want to identify a particular browser by name to open the URL, I could have specified one using the following syntax. (Here I'll request the Internet Explorer browser.)

      System.Diagnostics.Process.Start("IExplore.exe", _   

      Two arguments are used here with the Start method, separated by a comma. The exact location for the program named IExplore.exe on my system isn't specified, but Visual Basic will search the current system path for it when the program runs.

      Or if I had wished to run a different application with the Start method, such as the application Microsoft Word (and open the document c:\myletter.doc), I could have used the following syntax:

      System.Diagnostics.Process.Start("Winword.exe", _

      As you can see, the Start method in the Process class is very useful, and we'll make use of it again in this book. Now that you've entered your code, save your project and run it. (If you experimented with the Start syntax as I showed you, restore the original code shown at the beginning of step 8.)

    16. Click the Save All button on the Standard toolbar to save your changes.

    Run the WebLink program

    1. Click the Start button on the Standard toolbar to run the WebLink program.
    2. The form opens and runs, showing its Web site link and handsome title bar text.

    3. Click the link to open the Web site shown (www.microsoft.com/mspress/).
    4. Recall that it is only a happy coincidence that the link label Text property contains the same URL as the site you named in the program code. You may enter any text you like in the link label. You can also use the Image property for a link label to specify a picture to display in the background of the link label. Look on the following page to see what the Microsoft Press Web page looks like (in English) when the WebLink program displays it .using Internet Explorer.

      (Image Unavailable)

    5. Display the form again. (Click the Web Link Test form icon on the Windows task bar if the form isn't visible.)
    6. Notice that the link now appears in a dimmed style. Like a standard Web link, your link label communicates that it has been used (but is still active) by the color and intensity that it appears in.

    7. Click the Close button on the form to quit the test utility.
    8. You're finished writing code in this chapter.

    One Step Further: Installing ActiveX Controls

    Visual Studio .NET is a new product, so many developers will find that the current list of Windows Forms controls isn't as extensive as the ActiveX controls that were available to Visual Basic 6 programmers. If you want to expand the collection of controls that you have access to in Visual Studio .NET, you can load and use older ActiveX (COM) components and controls. These customizable programming tools were provided by Visual Basic 6, Visual C++ 6, Microsoft Office, and other third-party products. When you add older ActiveX controls to your Toolbox, Visual Studio displays them with the .NET controls, and you can use the ActiveX controls on your forms with few limitations. The only technical qualification is that Visual Studio must create a wrapper for the control, which makes the objects in the control usable in a .NET program. In most cases, Visual Studio .NET handles the creation of a control wrapper automatically when the ActiveX control is loaded.

    ActiveX controls on your computer typically have an .ocx or .dll filename extension. These library files are routinely added to your system when you install a new application program, and you can reuse them in your own programs if you can figure out how to use the objects, methods, and properties that they provide, or expose. Visual Studio .NET "learns" about the presence of new ActiveX controls when they are cataloged in the Windows system registry.

    The Microsoft Chart Control

    You probably have numerous ActiveX controls on your system now, especially if you have a previous version of Visual Basic or Microsoft Office on your system. Try installing one of the ActiveX controls now, even if you're not sure how to use it yet. (You'll start putting ActiveX controls to work later in the book, so you should learn the installation technique now.) The control you'll open in this exercise is the Microsoft Chart control, which allows you to build charts on your forms. The Microsoft Chart control is included in several versions of Microsoft Office. If you don't have Office or this control, pick another one.

    Install the Chart control

    1. If you still have the Code Editor open for the WebLink project, display the form.
    2. Click the Toolbox, and open the tab to which you would like to add an ActiveX control. For example, click the Windows Forms tab.
    3. ActiveX controls are added to individual tabs in the Toolbox so that you can remember where they are. Once on a Toolbox tab, they look just like regular controls in Visual Studio .NET.

    4. Click the Windows Forms tab again with the right mouse button, and then click the Customize Toolbox command on the pop-up menu.
    5. The Customize Toolbox dialog box opens.

    6. Click the COM Components tab in the Customize Toolbox dialog box.
    7. You'll see a long list of ActiveX components and controls that is unique to your system. The components appear in alphabetical order.

    8. Scroll to the Microsoft Office Chart 9.0 control, or another control that looks interesting, and then click the check box next to the control.
    9. Your dialog box will look similar to the illustration on the following page.

      (Image Unavailable)

    10. To add additional controls to the Toolbox, simply click check boxes next to the controls that you want.

    11. NOTE:
      Not all the components listed in the Customize Toolbox dialog box are designed to work in the Toolbox, so they may not work properly when you try to use them.

    12. Click OK to add the selected ActiveX control (or controls) to this project's Toolbox.
    13. The control will appear at the bottom of the Toolbox list. The control will appear for this project only and won't appear in other projects.

    14. Click the down scroll arrow in the Toolbox to see the newly added control as shown here:
    15. (Image Unavailable)

      The Microsoft Office Chart ActiveX control is available in several different versions and is included with applications such as Office 2000 and Office XP. You'll find that most ActiveX controls work just like the standard controls in the Visual Basic .NET Toolbox. In fact, if you didn't know they were ActiveX controls, it would be difficult to tell them apart from the default controls in Visual Studio .NET. Each ActiveX control has adjustable property settings and methods that you can call just like the other controls you've used in this chapter.

    Chapter 3 Quick Reference

    ToDo this
    Create a text boxClick the TextBox control, and draw the box.
    Create a buttonClick the Button control, and draw the button.
    Change a property at runtimeChange the value of the property by using program code. For example: Label1.Text = "Hello!"
    Create a radio buttonUse the RadioButton control. To create multiple radio buttons, place more than one button object inside a box that you create by using the GroupBox control.
    Create a check boxClick the CheckBox control, and draw a check box.
    Create a list boxClick the ListBox control, and draw a list box.
    Create a drop-down list box Click the ComboBox control, and draw a drop-down list box.
    Add items to a list boxInclude statements with the Add method in the Form1_Load event procedure of your program. For example: ListBox1.Items.Add "Printer"
    Display a Web pageCreate a link to the Web page using the LinkLabel control, and then open the link in a browser using the Process.Start method in program code.
    Install ActiveX controlsRight click the Toolbox tab that you want to place the control in, and then click the Customize Toolbox command. Click the COM Components tab, place a check mark next to the ActiveX control that you want to install, and then click OK.

Meet the Author

Michael Halvorson has written more than 30 books, including the popular Microsoft Visual Basic 2008 Step by Step, Microsoft Office XP Inside Out, and Microsoft Visual Basic 6.0 Professional Step by Step. A former Visual Basic localization manager at Microsoft, Michael is a professor at Pacific Lutheran University.

Customer Reviews

Average Review:

Post to your social network


Most Helpful Customer Reviews

See all customer reviews

Microsoft Visual Basic .NET Step by Step 4.6 out of 5 based on 0 ratings. 8 reviews.
Anonymous More than 1 year ago
Guest More than 1 year ago
This book is very well written and easy to follow. I am a new vb.net programmer and this book helped tremendously. Very well done.

If you are a biginner, this is the right book to get. I don't know about other VB.NET books. But I certainly recommend this one. Very easy, Very clear, informative, and very Step by Step.

Guest More than 1 year ago
I found this book useful in that it covers how to use the VS IDE to get the job done. This is a big help when you know what to code but not how to interact with the new IDE and tools.
Guest More than 1 year ago
This book is very well written and easy to follow. I am a new vb.net programmer and this book helped tremendously. Very well done. Enough said...
Guest More than 1 year ago
If you have no clue about programming in Visual Basic .Net or other language, BUY THIS BOOK. This is really a Step by Step instruction book.
Guest More than 1 year ago
This book is a great book to get you up to get your feet wet in the .NET framework. It takes you step by step by examples and instructions
Guest More than 1 year ago
This is an excellent book for the rank beginner as it has a very slow pace to give you time to absorb the information. The book makes no assumptions about previous knowledge like so many others seem to do. The examples work well and aren't cluttered with extra code to confuse you. The only flaw is the 'old style' use of variables. The code examples at first make no use of what has become the accepted standards for variable naming with prefixes in VB (examples: strName, intMyVariable) but instead uses simple ones like X, Y, MyName, etc... Whether this is intentional or not I don't know. Perhaps the examples were taken from old Visual Basic and updated for .NET rather than written fresh. This is not too big a gripe as the new naming systems can be confusing for a beginner, perhaps that is why it is not done at first. Experienced programmers will want to pass this book up if they need a more accelerated way to transition to VB .NET
Guest More than 1 year ago
If you have more than a passing familiarity with VB 6 this book, by itself, isn't for you. If, on the other hand, you're new to Visual Basic the book is excellent. It walks through a variety of basic programming techniques and illustrates a variety of useful controls in the process. If you are familiar with VB6 and looking to get started with VB.NET then I recommend you buy this book in the boxed set that includes the VB.NET Standard Edition. The software alone almost equals the cost of the boxed set so you end up saving money by getting the book as well. I bought the set for the software, skimmed through the book in a couple of days (focusing on the "Upgrade Notes" sections at the beginning of each chapter) and then moved on.