+ All Categories
Home > Documents > Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET...

Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET...

Date post: 15-Jul-2020
Category:
Upload: others
View: 2 times
Download: 0 times
Share this document with a friend
28
Creating Your First Windows Application In this chapter Setting Up a New Windows Project 23 Designing the User Interface 26 Coding Your Program’s Actions 38 Running Your Program 45 From Here… 46 2 CHAPTER ISBN: 0-558-13856-X Special Edition Using Visual Basic ® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.
Transcript
Page 1: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

Creating Your First WindowsApplicationIn this chapter

Setting Up a New Windows Project 23

Designing the User Interface 26

Coding Your Program’s Actions 38

Running Your Program 45

From Here… 46

2CHAPTER

04 572x CH02 11/29/01 2:10 PM Page 21

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 2: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

22 Chapter 2 Creating Your First Windows Application

You have probably read programming books that walk you step-by-step through the processof creating your first program. Typically, you create some form of the classic “Hello,World!” application. In this extremely simple example, the user is asked to initiate someaction such as clicking a button or pressing a key, and the computer responds with a messagesuch as “Hello, World!” A slightly more advanced variation asks for the user’s name andresponds with a customized greeting like “Hello, Lauren!”

Although examples like this might be sufficient for demonstrating that you can indeed use aprogramming language to create a program, the resulting application isn’t very useful. Ourapproach is to begin with a sample program that not only demonstrates the fundamentals ofcreating a Visual Basic .NET application, but also can be used in the real world.

In this chapter, you’ll create a Windows-based Loan Calculator program that calculates theperiodic payment needed to repay a loan, based on various factors such as the loan term andinterest rate. Your users will be able to input and modify values for these and other variablefactors, perform the calculation, and view the results. In addition, they will be able to viewan amortization schedule for the entire life of the loan.

The application you’ll be creating was adapted from a shareware program I wrotenamed “My Amortizer.” With proper planning and design, Visual Basic .NET can beused to create commercial-quality software applications.

Before you begin, take a look at what the final product will look like. Figure 2.1 shows theLoan Calculator’s main screen as it’s being used.

Figure 2.1The Loan Calculatorprogram offers theuser a variety ofoptions.

04 572x CH02 11/29/01 2:10 PM Page 22

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 3: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

23Setting Up a New Windows Project

Setting Up a New Windows ProjectTo develop a Visual Basic .NET application, you must first enter the Visual Basic .NETdevelopment environment, then set up a project. In Visual Basic terminology, a project acts asa repository for all the files needed to create an application.

Starting Visual Basic .NETBegin by starting the Visual Basic .NET Integrated Development Environment (IDE).When Visual Basic .NET’s IDE opens, you will normally see the Get Started pane of theVisual Studio Start Page, shown in Figure 2.2.

2

IPart

Ch

Figure 2.2A new Visual Basic.NET session displaysthe Visual Studio StartPage.

If this is the first time you have ever started Visual Basic .NET, you may see the MyProfile pane of the Visual Studio Home Page instead of the Get Started pane (seeFigure 2.3). If this is the case, simply click the Get Started link on the left side of thepage.

04 572x CH02 11/29/01 2:10 PM Page 23

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 4: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

24 Chapter 2 Creating Your First Windows Application

Creating A New ProjectClick the Create New Project button to start a new Visual Basic .NET project. You will bepresented with the New Project dialog box, as illustrated in Figure 2.4.

Figure 2.3If you have neverstarted Visual Basic.NET before, youmay see a differentpart of the VisualStudio Start Page.

Figure 2.4The New Project dia-log box assists you inthe setup of a newproject.

As you will learn in the course of reading this book, Visual Basic .NET allows you to createa number of different types of projects. For our example, we will be creating a standardWindows application that can run on the Microsoft Windows platform.

Process the New Project dialog box as follows:

� In the Project Types box, make sure Visual Basic Projects is selected.

� In the Templates box, click Windows Application.

04 572x CH02 11/29/01 2:10 PM Page 24

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 5: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

25Setting Up a New Windows Project

� In the Name text box, type the name by which you want your project to be known. Forthis example, we’ll use the name Loan Calculator.

� Make sure the Location box contains the path to the folder where you want to storeyour Visual Studio projects. When Visual Studio .NET is first installed, the default pro-ject location is the Visual Studio Projects subfolder of your My Documents folder; how-ever, you can change this location by clicking the Browse button (or by typing a validpath). A subfolder for this new project will be created in that location, as reported justbelow the Location box (“Project will be created at...”).

After you have completed filling out the New Project dialog box, click OK. Visual Basic.NET will create the files needed for your new project, create the appropriate subfolder, andsave the project files in that subfolder. You will then see the main Visual Basic .NET designscreen, as shown in Figure 2.5.

2

IPart

Ch

Figure 2.5Visual Basic .NET’sdesign screen iswhere you build yourapplication’s userinterface.

Notice Visual Basic .NET’s title bar; specifically, the word [design] after Microsoft VisualBasic .NET. This means that you are in design mode (also known as design time), a name forthe time you spend designing your program. Later, when you run your program, VisualBasic .NET will be in run mode.

As in previous versions of Visual Basic, a new Windows Application project consists of oneform, or window, which will typically serve as your program’s main user interface. VisualBasic applications are comprised of one or more components, such as forms, code modules,and classes, along with controls and other components.

04 572x CH02 11/29/01 2:10 PM Page 25

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 6: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

26 Chapter 2 Creating Your First Windows Application

Look at the Solution Explorer in the upper-right area of the screen in Figure 2.5 and shownin Figure 2.6. It consists of a list of the contents of the current project. Because you’ve justbegun this project, it contains only a single form named Form1.vb. A project can grow toinclude many components; the Solution Explorer helps keep them organized. The last partof the text in Visual Basic .NET’s title bar—(Form1.vb [Design])—tells you that Form1 is thecurrent form active in the development environment, and that it, too, is in design mode.

Figure 2.6The Solution Explorerlists the componentsthat make up a pro-ject.

➔ To learn all about Visual Basic .NET’s development environment see “Understanding the DevelopmentEnvironment,” p. 75

Saving Your WorkUnlike previous versions of Visual Basic, and much to the delight of VB programmers,Visual Basic .NET names and saves the files that comprise a project before you begin work-ing on the project. By default, Visual Basic .NET is set to automatically save your projectfiles whenever you build and/or run a program. You can change this setting in the Projectsand Solutions section of the Environment folder in the Options dialog box, which can beaccessed by clicking Tools, Options in the menu system.

Designing the User InterfaceNow that you have set up your working environment, it’s time to design the user interface,which is the visual part of the program that your user sees and interacts with. Typically,when developing Windows applications, you design the user interface first and then writethe code that makes the program come alive.

Getting Information from the UserMost computer programs are interactive—they need to receive information from the useras well as provide information back to the user. A Windows-based Visual Basic programinteracts with its user through controls that are placed on the program’s form(s). A control isan object that interacts with the user or the program. Many of Visual Basic’s controls can beused to obtain input from the user.

04 572x CH02 11/29/01 2:10 PM Page 26

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 7: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

27Designing the User Interface

The user interface for the Loan Calculator program will be responsible for accepting input,displaying output, and initiating the loan calculations. You will utilize three of Visual Basic.NET’s most commonly used controls:

� TextBox controls—accept textual information needed from the user, and display cer-tain information back to the user.

� Label controls—act as captions, displaying information to the user. Labels are similarto text boxes, except that the user can’t edit the information presented in them.

� Button controls—the user can click these to initiate program actions. Users of previ-ous versions of Visual Basic should note that Button controls were previously calledCommandButton controls.

All these controls are part of the basic set of controls found in Visual Basic .NET’s Toolbox(see Figure 2.7).

2

IPart

Ch

Figure 2.7Visual Basic .NET’sToolbox contains thecontrols needed tobuild applications.

Adding a TextBox ControlThe TextBox control, also known simply as a text box, is (as its name implies) a box that dis-plays and accepts text. In a way, it’s similar to a text box you might find on a survey or appli-cation form, which is designed to accept input (from a pen or pencil) as well as displayinformation. The TextBox control is one example of how far programming languages haveadvanced. Earlier programming environments required a lot of work to exchange informa-tion with the user. One of the fundamental concepts of Visual Basic has always been that itworks in conjunction with Windows to take care of the mundane details of where text ispositioned on the screen, how it’s retrieved from the user, and so on. Your Visual Basic pro-gram simply needs to be concerned with the text in the text box; the control itself takes careof the rest.

04 572x CH02 11/29/01 2:10 PM Page 27

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 8: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

28 Chapter 2 Creating Your First Windows Application

Adding a Control to a Form

For a Visual Basic program to use a control, that control must be placed on a form. Foryour Loan Calculator program, begin by placing a TextBox control on the main form:

1. By default, the Toolbox automatically hides itself. To make the Toolbox appear, hoveryour mouse pointer over the vertically oriented Toolbox tab on the left edge of thescreen. The Toolbox will “fly in,” as shown in Figure 2.8.

Figure 2.8The Toolbox appearswhen you hover nearthe left edge of thescreen.

2. Click the tool for the TextBox control in the Toolbox.

3. Move the mouse pointer to the Form1 form, which will probably be partially obscuredby the Toolbox window. Note that the pointer changes to a crosshair with a tiny imageof a text box attached to it, indicating that you’re about to draw a TextBox control.

4. Click anywhere in a blank area of Form1. This will cause a default-sized (100 pixels wideby 20 pixels high) TextBox control to appear on Form1 at the point where you clicked(see Figure 2.9).

04 572x CH02 11/29/01 2:10 PM Page 28

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 9: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

29Designing the User Interface

The procedures used to add a TextBox control to a form are the same as those for drawingmost controls on a form.

Setting a Control’s Properties

After you have added a control to a form, you will usually want to set one or more of thecontrol’s properties. Properties are settings that control the appearance and behavior of anobject. For the text box you just added, you want to set the Name and Text properties.

The Name property is very important. It is used in program code to identify the control. Be-cause a program will likely have many controls of the same type, you can use the control’s Nameproperty to identify the particular control for which a particular code statement is written.

Every control must have a name, which is represented by the value of its Name property. Inaddition, every control on a particular form must have a unique name, unless it’s part of acontrol array. (Control arrays are covered in detail in Chapter 10, “Understanding WindowsForms”; for now, just make sure all your controls on a given form have unique names.)

Visual Basic assigns a default name to every control placed on a form. Because this is thefirst text box you’ve placed on this form, its default name is TextBox1. Subsequently placedtext boxes would be named TextBox2, TextBox3, and so on. It’s very good programming

2

IPart

Ch

Figure 2.9The new text boxappears on the formand is selected (noticethe sizing handles).

You also can add a control to a form by double-clicking the control’s Toolbox icon. Thisplaces a control directly on the form. You can then move and resize the control asdesired with the sizing handles, as described in the upcoming section, “Moving andResizing a Control.”

04 572x CH02 11/29/01 2:10 PM Page 29

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 10: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

30 Chapter 2 Creating Your First Windows Application

practice to change the default control names to be more descriptive. Assume, for example,you have three text boxes on a form that are used to accept a customer’s last name, firstname, and address. If you change the default names of TextBox1, TextBox2, and TextBox3 tosomething more descriptive, such as txtLName, txtFName, and txtAddress, it will be mucheasier to remember what each control’s purpose is when you (inevitably) must modify yourprogram’s code at some future date.

Note that the control names I suggested begin with the prefix txt. It’s common tobegin a control’s name with a three-character lowercase prefix denoting the type ofcontrol, the rest of the name describing the control’s purpose. Thus, when debuggingprogram code, it is immediately clear that txtLName refers to a TextBox control thatcontains last name information. Other commonly used prefixes include lbl for Labelcontrols and btn for Button controls.

To change the name of the first text box you placed on the form for the Loan Calculatorproject, you must first make sure the control is selected. The selected control is the one forwhich properties will be changed in the Properties window, which is found in the lower-right portion of the development environment. As you’ll see a little later, multiple controlscan be selected at the same time. You can tell whether a control is selected if it has a seriesof eight sizing handles around its borders. The selected control’s name also appears in theProperties window’s Object box, which is the drop-down list just below the Properties win-dow’s title bar. If the desired control isn’t selected, simply click it one time to select it.

Now that the control is selected, take a look at the Properties window, which is a list ofproperties that apply to the selected object at design time and the current values of thoseproperties. The left side lists the names of the properties that apply to the selected objectand that can be changed at design time; each property’s current value is denoted in the rightside of the Properties window.

By default, the properties listed in the Properties window are categorized according totheir function. Until you are more familiar with the properties that apply to the varioustypes of controls, I recommend that you switch the Properties window to its other dis-play option, which arranges the properties alphabetically by name. To do so, click theAlphabetic icon just below the Properties window’s Object box. Even if you do this,however, the Name property will appear at the top of the window due to its impor-tance.

Click the Name property. If you have sorted the Properties window alphabetically, the Nameproperty is located near the very top of the list (due to its importance). If your Propertieswindow is in Categorized view, you’ll find the Name property in the Design category.Clicking the Name property makes it the current property (note that the property name ishighlighted). Note the default value—TextBox1—of the Name property on the right side. Atthis point, you can simply type a new value for the Name property, or edit the existing value.

04 572x CH02 11/29/01 2:10 PM Page 30

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 11: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

31Designing the User Interface

Change the value of your TextBox control’s Name property by typing a more descriptivename—let’s use txtPrincipal, because the user will enter a principal amount here—andpressing Enter. Figure 2.10 shows the Properties window after making this change.

2

IPart

Ch

Figure 2.10Use the Propertieswindow to set valuesfor your controls’properties.

A TextBox control’s Text property represents the text that’s entered in the box—that is,what is displayed inside the box on the screen. As the user types in a text box while a pro-gram is running, Visual Basic constantly modifies the text box’s Text property to reflect thecurrent contents of the box. By default, a new text box contains its own name; your newtext box contains TextBox1 in its Text property (recall that TextBox1 was the control’s namewhen it was created). For the Loan Calculator program, you don’t want anything in theText property when the program starts; in other words, you want the box to start off empty.To accomplish this, locate the TextBox control’s Text property in the Properties window.Select the current value (TextBox1), and press the Delete key.

Property values appearing in boldface type in the Properties window are an indicationthat those specific properties’ values have been changed from their default (original)values.

Adding the Remaining Text Boxes

Now that you’ve added one TextBox control to the form, it should be a simple matter toadd the other text boxes that you need for your Loan Calculator program. Add three moretext boxes to the form; name them txtIntRate, txtTerm, and txtPayment. Clear their Textproperties as well.

The last text box you added, txtPayment, will be used to display the calculated payment tothe user. Therefore, the user should not be able to type in that box. A text box’s ReadOnlyproperty is designed to prevent the user from being able to change text in a text box at run-time. Locate the ReadOnly property for txtPayment. Note that its default value is False,which allows the user to modify the control’s contents. Use the drop-down arrow to change

04 572x CH02 11/29/01 2:10 PM Page 31

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 12: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

32 Chapter 2 Creating Your First Windows Application

the ReadOnly property to True. Notice that the TextBox control on the form has nowbecome grayed-out. This is a visual clue to the user that he cannot enter that text box.

When you’re done, your form should look similar to the one shown in Figure 2.11.

Figure 2.11The interface of theLoan Calculator pro-gram has four textboxes.

If your form doesn’t look exactly like the one in Figure 2.11, don’t worry. One nice thing about avisual design environment is that you can change the appearance of objects quite easily.

To draw multiple controls of the same type, hold down the Ctrl key when you selectthe control’s tool in the Toolbox. That tool will remain selected in the Toolbox evenafter you’ve finished drawing a control. You can keep drawing multiple instances ofthat control without having to reselect the tool. When you’re through drawing that con-trol, select the Toolbox’s pointer tool to return the mouse pointer to its normal state.

Moving and Resizing a Control

If you don’t like where a control is positioned, simply use the mouse to drag it to a newlocation.

If you want to change the size of a control, you must first select it, which causes the sizinghandles to appear. You can then use the mouse to change the control’s size by dragging thesizing handles. The handles on the control’s top and bottom edges change its height. Thehandles on the control’s left and right edges change its width. The handles on the control’scorners change its height and width simultaneously.

By default, some controls (including the TextBox control that we are working with rightnow) have only two of the eight sizing handles activated; the others are grayed-out.That’s because the TextBox control’s AutoSize property is set to True by default. TheAutoSize property automatically controls the height of a TextBox control based uponthe size of the font used for the text that will be displayed by the control. Therefore,the sizing handles that affect the control’s height are not available.

04 572x CH02 11/29/01 2:10 PM Page 32

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 13: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

33Designing the User Interface

You also can change the size and position of objects by modifying their Size and Locationproperties, respectively, in the Properties window:

� An object’s Size property consists of a pair of two numbers that reflect the object’sheight and width, respectively (in pixels). Clicking the plus sign next to the name of theSize property in the Properties window will allow you to enter Width and Height prop-erties individually.

� An object’s Location property consists of a pair of two numbers that reflect the object’sx-position (distance from the left edge of its container to the left edge of the object) andy-position (distance from the top edge of its container to the top of the object), respec-tively (in pixels). Clicking the plus sign next to the name of the Location property inthe Properties window will allow you to enter X and Y properties individually.

Moving a Group of Controls

Now that you have created text boxes for the user’s input, you should label them so that theuser knows what to enter in each box. This will involve adding Label controls to the form.Depending upon where you drew the TextBox controls, you may need to move them to theright to ensure that there is enough room for the labels on the left. You could drag each textbox individually; however, it is quicker to move them all together at the same time. You caneasily select them all and move the entire group. To do this, click one of the text boxes toselect it, and then hold down Ctrl while you click each of the others. Notice that each textbox that you select in this manner gets its own set of sizing handles. After you have them all selected, begin dragging one of them. As you drag, the entire group is dragged at once.Drop the controls on the right side of the form; as you are dragging them, you will see out-lines of the selected controls being moved, as depicted in Figure 2.12.

2

IPart

Ch

Figure 2.12Selecting multiplecontrols enables youto move themtogether as a group.

Instead of Ctrl+clicking multiple controls, you can select a group of controls by drawinga rectangle around them. Click and hold down the left mouse button in an empty areaof the form. Note that a “rubber-band” box stretches as you move the mouse. Drawthe box around all the controls you want to select.

04 572x CH02 11/29/01 2:10 PM Page 33

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 14: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

34 Chapter 2 Creating Your First Windows Application

Labeling Your Program’s ControlsObviously, the user needs to know which values are to be entered into each of the textboxes. The easiest way to do this is to add a Label control next to each text box. The labelwill then act as a caption for the text box, containing a brief description of what data is to beentered there.

Although the user perceives Label controls and TextBox controls to be quite different, theyare very similar from a programmer’s perspective. They can both contain the same types oftext, although the text in a Label control can’t be modified by the user. However, by settingvarious properties of a Label control, the appearance of the text contained in it can be alteredin many ways. Figure 2.13 illustrates several Label controls demonstrating a variety of looks.

Figure 2.13Labels can take onmany different sizesand appearances.

To continue our earlier analogy of a survey form, Label controls are like the words that arepreprinted on the form to identify the purpose of the text boxes. The key differencebetween a Label control and a TextBox control is that a Label control contains text that theuser cannot change. As with a TextBox control, the text contained in a Label control isstored in its Text property.

In previous versions of Visual Basic, the text displayed in a Label control was containedin a property called Caption. Effective with Visual Basic .NET, Label controls have aText property instead.

To add a Label control to a form, follow these steps:

1. Hover over or click the Toolbox tab so the Toolbox is displayed.

2. Select the Label control’s tool in the Toolbox.

3. Click a blank area of the form to place a Label control on it.

4. In the Properties window, change the Label control’s Name property to lblPrincipal.

5. Change the Label control’s Text property to Principal.

04 572x CH02 11/29/01 2:10 PM Page 34

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 15: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

35Designing the User Interface

6. Change the Label control’s TextAlign property to MiddleRight, using the drop-downarrow next to the property setting (see Figure 2.14). This makes the label align its cap-tion along the middle of the right side, next to its corresponding text box, as is commonwith caption labels.

2

IPart

Ch

Figure 2.14Clicking the drop-down arrow for theTextAlign propertyallows you to visuallyspecify the alignmentof the label’s text.

7. Resize and reposition the label so it is fairly well lined up with the first text box.

You should now be able to see how the Label control will aid the user in determining whatto type in the first text box. Create three more Label controls, one for each of the remain-ing text boxes. Use the recommended values for the Name and Text properties outlined inTable 2.1 (don’t forget to set the TextAlign property as well). When you’re finished, yourform should look like the one shown in Figure 2.15.

Table 2.1 Name and Text Properties for the Loan Calculator Program’s Label Controls

Name Property Text Property

lblPrincipal Principal:

lblIntRate Annual Interest Rate (%):

lblTerm Term (Years):

lblPayment Monthly Payment:

Because lblIntRate has a longer caption in its Text property, you may need toresize the label to make it wider so all the text will fit on one line.

04 572x CH02 11/29/01 2:11 PM Page 35

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 16: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

36 Chapter 2 Creating Your First Windows Application

Changing a Form’s PropertiesJust as you define a control’s appearance and behavior by setting its properties, you also canset the properties of a form to govern its appearance and behavior.

Just like controls, forms have a Name property. The default name for a project’s first form isForm1; subsequently added forms are named Form2, Form3, and so on. Because there is onlyone form in this project, we will leave its name as the default Form1.

The form’s Text property governs what is displayed in the form’s title bar. Change the form’stitle bar for our sample application by setting the Text property to something more descrip-tive, like Loan Calculator Example.

If you need to change the size of your Loan Calculator form to accommodate the controlsyou added, you can do so using the techniques for resizing objects described earlier in thischapter.

Adding Command ButtonsSo far, your sample application’s form has a set of text boxes to accept the user’s input and aset of labels to identify those text boxes. You also need some way for the user to initiateactions—this is the purpose of Button controls. A user can click a Button control, also com-monly known as a command button (or simply a button), to cause something to happen. Youcan add a button to a form just like you add other controls—by using the mouse to draw it.

Like text boxes and labels, command buttons have a Text property that enables you to spec-ify the text that will appear on the button’s face, so the user will know what the button does.

To complete the interface of the Loan Calculator program, use the Toolbox’s Button controltool to add two buttons near the bottom of the form. Set their Name and Text propertiesaccording to Table 2.2. Figure 2.16 shows the completed Loan Calculator interface.

Figure 2.15The Loan Calculatorprogram’s labelsshow the user what toenter in the textboxes.

04 572x CH02 11/29/01 2:11 PM Page 36

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 17: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

37Designing the User Interface

Table 2.2 Name and Text Properties for the Loan Calculator Program’s Button Controls

Name Property Text Property

btnCalculate Calculate Payment

btnExit Exit

2

IPart

Ch

Figure 2.16After you have addedthe Button controls,the Loan Calculator’sinterface is complete.

Keeping Your Project SafeNow that you’ve completed designing the Loan Calculator’s interface, this would be anexcellent time to save your work so far. Because Visual Basic .NET automatically saved yourfiles when the project was created, resaving it is very easy—and highly recommended. Infact, it makes sense to save your work regularly throughout the development process. Younever know when you’ll have problems; a quick save only takes a few seconds, and couldsave you a lot of work when those problems do happen.

To resave your project, choose File, Save All from the menu system, or simply click the Save Allbutton on the toolbar. Because you’ve already told Visual Basic .NET where to save the filesthat make up your project, they’re automatically saved in the same location, using the same file-names. If you have added new components (forms, modules, and so on) since the last save, youwill be prompted for a filename and location for each of the newly added components.

As with lblIntRate, you may need to widen btnCalculate to accommodate itswider caption.

04 572x CH02 11/29/01 2:11 PM Page 37

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 18: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

38 Chapter 2 Creating Your First Windows Application

Coding Your Program’s ActionsAs mentioned earlier, the user interface of the Loan Calculator program is now complete.However, it doesn’t actually do anything at this point. For your program to become func-tional, you need to write some code. The term code—as it is used in this book—refers to oneor more lines of programming commands, written in a particular programming language(Visual Basic, in our case).

Responding to EventsVisual Basic is an object-oriented, event-driven language. This means that a program’s inter-face is comprised of objects (controls, forms, and so forth); the program is taught whatactions to perform when events happen to those objects.

An event is usually initiated by the user. By anticipating the possible events that can (andshould) occur to the various objects in your program, you can write code to respond tothose events appropriately. For example, in the case of a Button control labeled Exit, yourcode should respond to that button’s Click event by ending the program. This code shouldexecute whenever the Exit button’s Click event occurs.

You cause a program to respond to events by placing code in event handlers. An event han-dler is a sub procedure, or standalone block of code, that is executed when a particular eventoccurs to a particular object. In the case of a user clicking an Exit button, you need to addcode to the Exit button’s Click event handler. Let’s illustrate this by writing code for theClick event handler of your Loan Calculator program’s Exit button.

Double-click the Exit button (btnExit) that you placed on the sample application’s form.You’ll see a new window called a Code window (see Figure 2.17). You can open a separateCode window for each form (or other kind of module) in your project, and this is where youplace code that relates to that form and the objects contained in it. Notice that the Codewindow already contains a small amount of code. This prewritten code has to do with howWindows manages Windows forms.

Because you double-clicked on the Exit button to enter the Code window, your cursorshould be automatically placed in the event handler for the Exit button’s Click event.Specifically, you should find your cursor in the middle of a sub procedure, beginning withthe words Private Sub and ending with the words End Sub. A sub procedure (also known sim-ply as a procedure) is a discrete sequence of code statements that has a name and is executedas a unit.

04 572x CH02 11/29/01 2:11 PM Page 38

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 19: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

39Coding Your Program’s Actions

The part after the words Private Sub denotes the sub procedure’s name. This particular subprocedure is named btnExit_Click, a predefined name that denotes that it is the Click eventhandler for the control named btnExit. (There is also some more information after the proce-dure name; don’t be concerned with this right now.) Visual Basic .NET will execute any codelocated within this sub procedure whenever the Click event occurs to this Button control.

2

IPart

Ch

Sub procedurename

Figure 2.17The Code window isa full-featured editorfor the code thatrelates to your pro-gram’s objects.

Most objects can react to one of several different events. Each type of object has adefault event, which is the event that usually occurs to that type of object most often.For example, the Click event is the one that occurs most often to a Button control.The default event is the one that is opened in the Code window when you double-clickan object that doesn’t already have any code associated with it.

To cause the program to end when the user clicks the Exit button, you simply need to addone line of code—Visual Basic’s End statement—to the btnExit_Click procedure. Your cur-sor should already be on the blank line between the Private Sub btnExit_Click() and EndSub statements; if it’s not, simply click there. Press Tab twice to indent the code (that makesit easier to read), then type the word End. Press Enter to insert a new blank line into theprocedure (this isn’t necessary, but the extra blank line improves readability). When you’redone, your complete sub procedure should look like this code:

Private Sub btnExit_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnExit.ClickEnd

End Sub

04 572x CH02 11/29/01 2:11 PM Page 39

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 20: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

40 Chapter 2 Creating Your First Windows Application

Congratulations! You just wrote your first Visual Basic code.

Specifying Event HandlersLook at the two drop-down list boxes near the top of the Code window, as shown in Figure2.18. The Class Name box (the one on the left) lists all the objects that have been placed onthe current form, as well as two special sections named Base Class Events (which representsthe form itself) and Overrides. The options available in the Method Name box (on the right)change based upon which object is currently selected in the Class Name box.

You should see Form1 (Loan_Calculator) selected in the Class Name box; this indicates thatthe current code window relates to the Form1 object in the Loan Calculator project. TheMethod Name box should display btnExit_Click, indicating that you are currently editingthat event handler.

Using these two drop-down list boxes enables you to navigate to any portion of the Codewindow. Think of the code for a particular form as one long text file; the Code window is anavigation tool that helps you quickly display a specific object/event combination.

Due to printing requirements, the first line of code (Private Sub btnExit...),which will appear as a single line of code in your Code window, appears as two sepa-rate lines as printed earlier. We have broken the single line into two by using theunderscore (_), which Visual Basic recognizes as the code continuation character.Visual Basic treats two (or more) lines joined by an underscore as a single line of code.

Figure 2.18The Exit button’sClick event handlerwill cause the pro-gram to end when thebutton is clicked.

Method Name boxClass Name box

04 572x CH02 11/29/01 2:11 PM Page 40

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 21: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

41Coding Your Program’s Actions

When you double-click a control at design time, the Code window automatically opens tothe procedure that serves as the event handler for the default event of the control youclicked, unless some event other than the default already has code in its event handler. Inthat case, the event handler that contains code is selected, in case you want to edit that code.Of course, you can use the Class Name and Method Name boxes at any time to quicklylocate the desired object/event combination.

2

IPart

Ch

In addition to double-clicking an object, you can also open the Code window by press-ing F7, by clicking the View Code button in the Solution Explorer window, or by select-ing View, Code from the Main menu.

Now that you’ve properly coded the Exit button to end the application, all that remains isto code the Calculate Payment button (btnCalculate). Its function is to calculate themonthly payment amount based on the information that the user has supplied. This codewill be written as the Click event handler for the Button control btnCalculate. You coulddisplay the btnCalculate button’s Click event handler by bringing the form designer to thefront and double-clicking btnCalculate; however, because the Code window is alreadyopen, you might find it more efficient to drop down the Code window’s Class Name boxand select btnCalculate, then use the Method Name box to select the Click event. Thisdisplays the btnCalculate_Click event handler in the Code window.

Writing Program CodeThe procedure that calculates the loan payment will be more complex than the Exit proce-dure. Obviously, the code that performs the payment calculation needs to be more involvedthan a simple End statement. Also, you must do some additional housekeeping in this proce-dure, as you will be using variables.

A variable is a temporary storage location for information. Very often, your programs willneed to remember information—such as calculation results, the user’s name, order totals,and so on—as the program is running. Think of a variable like a white board that the pro-gram can use to remember information. Within certain guidelines, the program can writeinformation on the white board, modify that information, even erase it completely. Oneimportant consideration is that when the program finishes, the white board is always erasedcompletely.

➔ For more information about variables, see Chapter 6, “Storing Information in Variables,” p. 139

Variable Declarations

The first part of the Calculate sub procedure will be used to declare the variables you’llneed. That means that you will tell Visual Basic the names of the variables that the proce-dure will be using, as well as what type of information each variable may contain. By default,Visual Basic .NET requires you to declare your variables. A program will not run if youhave used variables that you did not declare. You can turn this option off, but it’s always

04 572x CH02 11/29/01 2:11 PM Page 41

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 22: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

42 Chapter 2 Creating Your First Windows Application

good practice to force yourself to declare your variables before using them. This helpsreduce the need for debugging problems caused by misspelled variable names.

Your Calculate procedure uses four variables—one each to hold the principal amount, theinterest rate, the loan term, and the calculated monthly payment. Make sure the cursor is onthe blank line between Private Sub btnCalculate_Click() and End Sub. Press Tab toindent the code, then type the following line:

Dim decPrincipal As Decimal

Notice that when you press Enter after typing this code, the cursor doesn’t go back to theleft margin of the code window. The code editor assumes that you want to indent the nextline of code to the same level as the preceding line. This aids in your code’s readability. Youcan increase the level of indent by pressing Tab; Shift+Tab or Backspace will decrease theindent level.

As you can tell from this code, the general format for declaring variables is the word Dim,followed by a variable name, the word As, and the variable’s type. As with object names, youshould follow a naming standard. Throughout this book, we’ll use a very common variablenaming standard that uses the first three (lowercase) characters of the variable name as aprefix designating its type; the remaining portion of the variable’s name (usually beginningwith an uppercase character) describes its purpose. The variable named decPrincipal, forexample, is a Decimal type variable that will store the principal amount. Some variable typesand their common prefixes are outlined in Table 2.3.

You may have noticed that when you typed the space after the word As, a list of differ-ent types appeared on the screen. This feature helps you select an applicable keywordas you are entering code. When you typed the d that begins the word decimal, thelist automatically moved to the keywords beginning with d. When the desired keywordhas been selected, you can simply press Enter (or click the keyword with the mouse),and the desired word is completed for you.

Table 2.3 Prefixes Used in a Common Variable Naming Convention

Prefix Variable Type

str String

int Integer

lng Long Integer

sng Single-precision Floating Point

dbl Double-precision Floating Point

dec Decimal (often used for money data)

bln Boolean (True/False)

var Variant

04 572x CH02 11/29/01 2:11 PM Page 42

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 23: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

43Coding Your Program’s Actions

Add the following line of code for the next declaration:

Dim decIntRate As Decimal

This would be a good time to point out that multiple variables can be declared on the sameline of code. Add the following line of code to declare two more variables:

Dim intTerm As Integer, dblPayment As Double

2

IPart

Ch

In previous versions of Visual Basic, each variable listed in a single-line declaration hadto have its own type specifically stated; otherwise, its type would have defaulted toVariant. In Visual Basic .NET, however, you can declare multiple variables of the sametype on a single line. For instance, the line

Dim intTest1, intTest2 as Integer

will declare both intTest1 and intTest2 as Integer types.

Procedure Code

The procedure code is the remaining part of the procedure that does the actual work. Inyour Loan Calculator program, this part of the procedure will be responsible for retrievingthe input values from the first three text boxes, calculating the monthly payment, and dis-playing the payment in the fourth text box.

Enter the following two lines into the Code window (after the variable declaration state-ments):

‘Store the principal in the variable decPrincipaldecPrincipal = txtPrincipal.Text

The first line is a comment explaining what’s going on. A comment is denoted by a singlequotation mark (‘), usually at the beginning of a line. When Visual Basic encounters a sin-gle quote on a line, the remainder of the line is ignored. Visual Basic then looks to the nextline for the next instruction.

The second line of this code retrieves the information that the user entered into thetxtPrincipal text box, placing the value into the variable decPrincipal. This is done withan assignment statement, much like an assignment statement in algebra—a variable appearson the left side of the equal sign, and the value to be placed in that variable appears on theright side.

To retrieve the information that the user entered into the txtPrincipal text box, we accessthe text box’s Text property. Recall how we set the Text property of our program’s textboxes to an empty string at design time. We also can access the Text property of a text boxusing code at runtime (while the programming is running) to capture what the user hasentered into the text box.

04 572x CH02 11/29/01 2:11 PM Page 43

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 24: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

44 Chapter 2 Creating Your First Windows Application

Enter the remaining code presented in Listing 2.1 in the Code window, between what youhave already entered and the End Sub statement. The comments should help you understandhow the code works. Figure 2.19 shows the completed sub procedure in the Code window.

Listing 2.1 Code to Calculate the Monthly Payment

‘Convert interest rate to its decimal equivalent‘ i.e. 12.75 becomes 0.1275decIntRate = txtIntRate.Text / 100

‘Convert annual interest rate to monthly‘ by dividing by 12 (months in a year)decIntRate = decIntRate / 12

‘Convert number of years to number of months‘ by multiplying by 12 (months in a year)intTerm = txtTerm.Text * 12‘Calculate and display the monthly payment.‘ If the interest rate is zero, the payment is‘ the principal divided by # of periods.‘ The Format function makes the displayed number look good.If decIntRate = 0 Then

dblPayment = decPrincipal / intTermElse

dblPayment = decPrincipal * _(decIntRate / (1 - (1 + decIntRate) ^ -intTerm))

End IftxtPayment.Text = Format(dblPayment, “$#,##0.00”)

Even though a TextBox control contains textual information and our decPrincipalvariable expects a numeric value, Visual Basic takes care of the data type conversionimplicitly.

As you enter the remaining code, you’ll notice several more comments within the codestatements. Again, a comment is a line of code that isn’t executed; rather, it’s used toexplain the purpose or functionality of the executable portions of the code. Comments,which are a form of documentation, help a programmer to quickly understand the pur-pose of a section of code when he or she must edit it at some point in the future. It’susually a very good idea to include a lot of comments in your code. You may thinkyou’ll remember why you solved a problem a certain way, but when you look at codethat you (or someone else) wrote weeks, months, or even years earlier, comments willmake the code’s purpose much clearer.

04 572x CH02 11/29/01 2:11 PM Page 44

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 25: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

45Running Your Program

Running Your ProgramI’ll bet you’re anxious to see your program in action! Before running it, however, make sureyou save your work so far. To run the program, you need to execute Visual Basic’s Startcommand using any of these methods:

� Click the Start button on the Visual Basic toolbar.

� Choose Debug, Start from the menu system.

� Press F5.

When you execute the Start command, Visual Basic compiles your program to check forcertain types of errors; if your Output window is visible, you will see the results as it buildsthe application. If no errors are found, the program will begin executing and you’ll see youruser interface. Notice in Visual Basic’s title bar that you’ve gone from Design mode to Runmode, meaning that the program is actually running. Because the application is object-oriented and event-driven, it’s waiting for you (the user) to cause an event to occur to anobject, such as typing in a text box or clicking a button.

Test your program by entering values for the principal, term, and interest rate. Use thesevalues for your first test:

Principal 128000

Interest Rate 9.75

Term 30

2

IPart

Ch

Figure 2.19Entering the code tocalculate the monthlypayment completesthe Click event handler forbtnCalculate.

04 572x CH02 11/29/01 2:11 PM Page 45

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 26: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

46 Chapter 2 Creating Your First Windows Application

After entering these values, click the Calculate Payment button. The monthly payment dis-played should be $1,099.72 (see Figure 2.20).

Figure 2.20The Loan Calculatorprogram is now fullyfunctional and cancalculate loan pay-ments.

Test the program with other combinations of numbers. When you’re through, end the pro-gram by clicking your application’s Exit button. This will return you to the design environ-ment.

From Here…The Loan Calculator program has enabled us to dive right in to writing a Visual Basic pro-gram from scratch. In this chapter, you learned how to do the following:

� Start Visual Basic

� Begin a new project

� Add controls to a form

� Set properties of your project’s objects

� Write code to bring the program to life

Believe it or not, these steps comprise the core of Visual Basic .NET programming for theWindows environment. You’ve seen simple examples of all these steps, but most VisualBasic programming involves repetition of these steps over and over until the desired resultsare obtained.

Because this program is a demonstration of basic programming techniques, its inter-face is quite simple, and very little effort has gone into making it error-proof. Numbersmust be typed without thousands separators or dollar signs for the calculations towork properly. As you develop your programming skills later in the book, you’ll seehow to overcome these types of limitations.

04 572x CH02 11/29/01 2:11 PM Page 46

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 27: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

47From Here…

As you start working with more complex applications, you’ll see many ways to practice andenhance these fundamental Visual Basic programming skills. Refer to the following chaptersfor additional related information:

� To see how to build an application much like this one for Web-based deployment, seeChapter 3, “Creating Your First Web Application.”

� To see how to use Visual Basic’s fundamental components to create your own applica-tions, see Chapter 4, “Understanding the Development Environment.”

� To learn more about the components that you use to build Visual Basic applications, seeChapter 5, “Visual Basic Building Blocks.”

2

IPart

Ch

04 572x CH02 11/29/01 2:11 PM Page 47

ISB

N: 0

-558

-138

56-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.

Page 28: Creating Your First Windows Applicationwps.pearsoncustom.com/wps/media/objects/6904/... · .NET session displays the Visual Studio Start Page. If this is the first time you have

04 572x CH02 11/29/01 2:11 PM Page 48

ISB

N: 0-558-13856-X

Special Edition Using Visual Basic® .Net, by Brian Siler and Jeff Spotts. Copyright © 2002 by Que. Published by Que Publishing.


Recommended