Visual Basic Programming
Visual Basic Programming
Goal 1:
Learning to program computers is so much fun it's euphoric. Do you remember how excited you were and how good you felt when you learned to ride your bike without someone holding the seat? Every time you finish a program you will feel that same sense of accomplishment and independence.
Goal 2:
You should understand the levels of thinking skills so you can decide for yourself where you want to be in the professional pecking order.
From the Bottom Up: Knowledge - Everything is built on this foundation. Read everything you can find. Comprehension - Grasping the meaning and usefulness of your knowledge. Application - The ability to apply your understanding of the facts. Analysis - Identify the problem and design a solution. Synthesis - Creating a solution. Evaluation - The ability to assess the solution.
Introduction
Page
Analysis, Synthesis, and Evaluation are referred to as the Higher Order Thinking Skills. This should be your target. This is where you should learn to work. The difference between the two is the difference between a draftsman and an architect, a technician and an engineer, a nurse and a doctor. In programming we have coders and software architects. Software architects usually have degrees in computer science, software engineering, or information systems where they learned to reason their way through a problem and design the best possible solution.
Goal 3:
I want to make you rich. You might think this is a come-on or a marketing ploy of some sort but it's not. I want to help you learn computer programming with Visual Basic and en route I want to show you how to become financially independent. The calculations are simple and I will use them in programming examples so you will learn Visual Basic and financial independence simultaneously.
General Premise:
Some books begin with the history of programming, the definition of terms, or the description of computer components. The fact you're reading this book tells me you probably know the difference between a mouse and a printer and if there's an historic point or term that will help you understand programming better I will point it out when it applies. Otherwise, I want to move thoroughly and quickly as possible through the material so we can get you on your way.
Introduction
Page
Introduction
Visual Basic may be one of the most popular programming languages of all time. Microsoft continues to extol Visual Basic as its premier Rapid Application Development (RAD) language. It is the most English like programming language and the least cryptic. That generally allows programmers of equal skill levels to produce programs in less time with Visual Basic than any other programming language. The less cryptic syntax also makes code easier to maintain. In the role of a businessperson who doesn't get paid until the project is delivered or a programmer who is judged on productivity and whose evaluations and raises depend on performance, Visual Basic is likely the most practical choice. Visual Basic can be used in different types of programming such as programs for a desktop or laptop computer and for developing websites and Internet applications. VB can also be used to program handheld devices and phones. Visual Basic has all the capability of any other programming language.
Introduction
Page
http://www.microsoft.com/visualstudio/en-us/products/2010-editions/product-comparison
Note: Please keep in mind that web addresses are subject to change without notice.
The discussions in this text are based on Visual Studio 2010 Ultimate. However, most of the code will work in Visual Basic 2010 Express or Visual Web Developer 2010 Express. The menus may vary slightly but not to the extent that it should be a problem. College and high school students may be able to get Visual Studio at dreamspark.com.
Page 6 Chapter 1
Page 7 Chapter 1
Before We Start
There are a few different options for menu schemes and to make sure you're using the same setup as the book go to the pull-down menu of Tools on the top menu strip. Select, "Import and Export Settings" and select, "Reset all settings" then Next. On the "Save Current Settings" page you have a choice to save your current options or to just reset everything. It doesn't hurt to save your existing settings just in case you want to recall that set later but unless you have made intentional changes to the setup you can just choose to reset the settings. Choose one and then pick Next. On the page titled "Choose a Default Collection of Settings" select, "Visual Basic Development Settings" and then Finish, then Close. You will now be using the standard menus designed for programming is Visual Basic and your screen should match the screenshots in the book.
Page 8 Chapter 1
Page 9 Chapter 1
In the Name box at the bottom of the window give your project a more meaningful name such as CreatingTheInterface or Chapter 1; something that will tie it back to the location in the book.
Page 10 Chapter 1
7. Solution Explorer
1. Title Bar - Displays the name of the current project. 2. Menu Bar - Contains the standard pull-down menus. 3. Standard Toolbar - The standard icon menu (there are several). 4. Toolbox - Contains controls that can be added to the form. 5. Main Work Area - Space provided for the form. 6. Windows Form - Contains controls for the user interface (UI). 7. Solution Explorer - Displays the files and resources in the project. 8. Selected Object - Displays the name of the selected object; currently the form. 9. Properties Window - Shows the current settings or properties of a specific object.
Page 11 Chapter 1
When a window is pinned down it is docked in a specific location. When a window is pinned or docked it can be dragged out of its location. Grab a docked window by placing the mouse on the window's title bar, hold down the left mouse button, and move it to the desired location. To move the Toolbox for example, just select its title bar, hold down the mouse button, and drag it to the preferred location.
Page 12 Chapter 1
If you have multiple monitors or a very large monitor you may want to drag a menu or multiple menus off to the side or to another monitor to give you more workspace in the main work area. Oooo now that's cool.
To drag a window back to its original location and redock it, simply grab the title bar and start dragging it back to the desired location. As you approach the docking area you will see an image on the screen that will allow you to choose where you want it docked. As you hover the mouse over the directional branches of the image, a shadowed area will appear indicating where the window will be docked if that part of the image is selected.
Page 13 Chapter 1
If at any time you want to return all of the windows to their default location simply go to the pulldown menu of Window, select Reset Window Layout, and answer Yes to the prompt. Now everything is back in its default location.
Page 14 Chapter 1
Adding Controls
Controls are the items in the Toolbox. To create the UI, controls are selected in the Toolbox and placed on the form. The form becomes the window of your project. There are a number of ways to get controls from the Toolbox onto the form. Let's start with a Button control. In the Toolbox, double-click on the Button control. A button appears on the form. You can drag the button to any location on the form. The second method is to drag a button from the Toolbox onto the form. Place the cursor over the Button control in the Toolbox, hold down the mouse button, and drag the button where you want it on the form. Another method is to single-click on the Button control in the Toolbox, move the cursor onto the form, select a point, and while continuing to hold the mouse button, drag the cursor to the diagonal corner of the button. This allows you to create any size button at the desired location.
Page 15 Chapter 1
Aligning Controls
Some people are very good at dragging controls around and getting to line them up perfectly. For the rest of us Microsoft created some pretty cool alignment tools. Layout a form with a button, a text box, and a label that looks something like this:
Drag the label to the left end of the text box. As the label nears the text box you will see a blue line appear. This is an alignment feature that is showing you that some part of the label is aligned with some part of the text box. Controls can be aligned by their edges and the by the top and bottom of the text location in the approaching controls. As you drag the label closer to the text box you will see another small blue line that snaps into place. This is the minimum recommended distance between the two controls. In the following diagram the bottom of the label is aligned with what will be the bottom of the text placed in the text box and you can see the snap line that separates them.
Page 16 Chapter 1
Copying Controls
To select the controls to copy you can either hold down the Shift key and pick them one at a time or pick a point on the form near the control and drag out a selection box that touches all of the controls to be copied. Use either method to select the label and the text box.
Notice the small squares that appear when the controls are selected. These are called grips. They are used to confirm that the control has been selected but they can also be used to change the size of the controls. Also notice that when multiple controls are selected, one of the controls has white grips and the rest are black. The white grips identify the dominant control. Whatever adjustments in size are made to the dominant grip will also be applied to the rest of the controls selected. We'll see that in the next example. There are a couple of ways to copy the selected objects. First, right-click on one of the selected objects and select copy. Move the cursor to a new location, right-click to bring up the context menu, and select paste. The new objects may not have been copied to the point you wanted but you can move them. Use Ctrl Z to undo the last event. The second method gives you more control. Select the label and text box again. This time hold down the Ctrl key and use the mouse to drag them to a position just above the original set. Make sure to use the blue snap line for spacing. Repeat the process until you have three sets of labels and text boxes. This method provides much greater control.
Page 17 Chapter 1
Resizing Controls
Before we resize the controls, let's move them to the upper left corner. Use the window method to select all three of the labels and text boxes. After all are selected single-click on the upper left label to make it the dominant control. Now drag the group to the upper left corner until you see the blue snap lines on the left and top of the dominant label.
Now we want to resize the text boxes. First we need to select a new group because the current group includes the labels. Pick a point below the text boxes and drag the window up until it touches all three text boxes. Put the mouse on the right grip of one of the text boxes and drag it to the right until blue a snap line appears between the text box and the right edge of the form. All three boxes are now the same size and properly aligned. Select the button and drag it just beneath the text boxes so that the snap lines hold it in place and to the right edge of the form.
Page 18 Chapter 1
To complete this layout example resize the form to look like the following example. To resize the form simply click the mouse anywhere on the form but not touching a control. Us the grip in the bottom center grip to adjust the height of the form. Unfortunately, no snap line will appear you must align this one manually.
You have just created a simple user interface. It doesn't do anything real just yet but this was the first step. If you want to see your program run look on the Standard Toolbar for the green triangle pointing to the right and select it with the mouse or you can just press function key 5 (F5). The new window represents your program. You can move it around the screen and change its size just like any other Windows program. To stop the program either select the blue square icon on the Standard Toolbar or pick the red X in the top right corner of the window.
Page 19 Chapter 1
Page 20 Chapter 1
When the Save Project window appears, leave the Name and the Solution Name as they are for now but notice where it saves the project by default: C:\Users\ComputerName\Documents\Visual Studio 10\Projects. You can change to another directory if you like or accept the default location. Also make sure you have a check in the box next to "Create directory for solution". That will help prevent getting this project mixed up with other projects and files.
You have now completed the design of a user interface and saved your project.
Page 21 Chapter 1
Summary
Concepts
The user interface is created in the Design View of the IDE. Controls are copied from the Toolbox to the form. Controls on the form can be moved, copied, and resized to create a form that is well organized, functional, and has a pleasing appearance.
Vocabulary
Control - An object in the Toolbox that has a visual image that can be placed on a form. Control + Shift + S - Saves all the files in the current project. Design View - The editor for the UI. IDE - Integrated Development Environment. Multiple programs that run in a single user interface providing the tools necessary to create computer applications. Menu Bar - Contains the standard pull-down menus. Main Work Area - Space provided for the form in the Design View. Map Pin - An icon located in the top right corner of some windows that determines whether a window stays open or hides when not in use. Properties Window - Shows the current settings or properties of a specific object. Selected Object - Displays the name of the selected object. Solution Explorer - Displays the files and resources in the project. Standard Toolbar - The standard icon menu (there are several others). Title Bar - Displays the name of the current project. Toolbox - Contains controls that can be added to the form.
Page 22 Chapter 1
UI - User interface. The window or screen on a computer monitor that provides buttons, text boxes, and other objects that an operator can use to interact with the program. Windows Form - Contains controls for the user interface (UI) and is the window displayed when the program runs.
Chapter Project
In this chapter we created a very simple user interface but we only used three controls. Create a new project, give it a name that tells you it's related to this chapter in this book and create the following UI.
Try to get comfortable working in the Design View. Once you've created the preceding project, delete some of the controls and add others. Experiment, get acquainted, have some fun.
Page 23 Chapter 2
Rename Form1
Let's just focus on the form for a moment. The form has Form1 on the title bar and the standard Minimize, Maximize, and Close buttons in the upper right corner. Look a little closer. The form is a little darker that the main work area, it has a border around it, it has an icon to the left of the title, and the form is fairly small. The first thing we want to change is the name of the file that contains the form in our project. Look at the Solution Explorer at the item named Form1.vb. Form1 is the name of the file and vb is the file extension that tells us what type of file it is; a Visual Basic (.vb) file. There are different ways to change the name of Form1.vb. 1. Right-click on Form1.vb in the Solution Explorer and select Rename. 2. Click once on the name Form1.vb in the Solution Explorer. Wait just long enough that the computer know you didn't mean to double-click and then select it again. The form name will be highlighted and you can type in the new name. 3. Select the filename Form1 in the Solution Explorer and then look at the Properties window. You can select the entry, "File Name", then just start typing the new name. 4. Double-click on the name Form1.vb in the Properties window to select if for renaming. Whichever method you choose, rename the file to SettingProperties.vb; no spaces. Don't leave off the .vb or Visual Basic will not recognize it as a form and the program will not run.
Page 24 Chapter 2
The file name can be more than one word but if only one word is used, the Name property of the form will inherit the name of the file. For example, if Form1.vb is renamed to SettingProperties.vb the Name property of the Form1 object will be changed to SettingProperties. If Form1.vb is renamed to Setting Propeties.vb (with a space), the Name property of the Form1 object will remain Form1. Notice that the name on the title bar of the form in the work area did not change when Form1.vb was renamed. We changed the name of the computer file that holds the image of the form and any code we develop for it later. Changing Form1 on the form object is a separate step. Locate the map pin on the Solution Explorer and select it with the mouse. That will allow it to retract to the right but it leaves a tab so it can be extended when needed. This allows us to see more of the Properties window for the coming example.
Select the Form1 object in the main work area. At the top of the Properties window you will see the word SettingProperties in bold letters and next to it, "System.Windows.Forms.Form". SettingProperties is now the name of the form object and System.Windows.Forms.Form is how the form is located in the library. We'll learn about libraries in a later chapter so for now we'll just be concerned with the name. Let's get a little better acquainted with the Properties window. There are four icons on the bar just below the name. The leftmost icon categorizes the properties in the window below into the various purposes of the properties. The next icon alphabetizes the properties by name. The first two icons give you a choice of how you want the properties listed. For our purpose we will use the alphabetized display.
Page 25 Chapter 2
The next two icons determine whether we are looking at properties or events; examine both. Events are in a later section so for now we will select properties. The rightmost icon is the Property Pages icon. Right-click on the icon and select Description. You'll see the box at the bottom that contains the description of the currently selected property disappears. Right-click on the icon again and turn the description box back on. Scroll to the top of the of the Properties window so you can see the Name property. The current name is SettingProperties. Place the cursor in front of the word Name in parenthesis, type frm in front of SettingProperties; all one word (frmSettingProperties), and hit Enter. That changed the Name property of the form but wait a minute. The name on the title bar of the form still says Form1. What we renamed was the form object. Look at the box near the top of the properties window. It should now say frmSettingProperties. In the Properties window scroll down until you see Text in the left column. The Text property is where the name on the title bar is set. Select the property name Text, type Properties Example, and hit Enter. The name on the title bar reflects the change. It is important to understand the difference between Form1.vb, the Name property for Form1, and the Text property that originally says Form1.
Form1.vb is the file on the disk that stores the image of the form, its properties, controls, and
its related code. We renamed it to SettingProperties.vb
Form1 is the name of the object in the Design View that holds the controls imported from the
Toolbox. Renamed: frmSettingProperties.
Form1
in the text property is the name that is displayed on the form's title bar. Renamed:
Properties Example. Having three separate but related items can be a little confusing to someone new to programming. I think we owe Microsoft a 'fuss' for that one.
Note: The frm is a three letter prefix that lets us know this is a form when we see it in code. This is part or a format created some years ago at Microsoft called Hungarian Notation.
There are three letter prefixes for all of the controls; a list of which can be found in the appendices. Note: Variable and object names can only be one word long. Programmers join words to provide a better description for the purpose of the variable or object such as frmSettingProperties. Two capitalization methods are generally used for these joined words or phrases.
Page 26 Chapter 2
The first is camel case where the first word begins with lower case and all subsequent words are capitalized such as frmSettingProperties or btnExit (the Exit button). camelCase is used to name parameters. The second method is Pascal Case which capitalizes all words in the phrase such as SetClock, ReadDate, and GetData. Pascal case is used for items in the following list: Classes Exceptions Namespaces Enumerations Interfaces Properties Events Methods More to come http://msdn.microsoft.com/en-us/library/x2dbyw72(v=vs.71).aspx These are terms and concepts that will be covered in future sections so if you don't recognize them, do not be concerned.
Page 27 Chapter 2
Appearance
The form doesn't look bad but we want to make it our own creation so let's change the look of the form. One of the properties that is important to set early in the design process is the
Font property.
It's important to set it because any control we add to the form will inherit the font style from the form. Scroll down until you find the Font property. Notice the arrow to the left of Font. The arrow indicates there is a list of other properties associated with the Font and to see them we need to select it. When you select the arrow you will see the additional properties. Notice that a button appears on the right side or the row containing three dots. The three dots are called an button.
ellipsis and they indicate there is a menu associated with the button.
Select the
When you select the button the Font dialog box appears. In this dialog box you can set almost all of the properties you could from the properties window but not all. Scroll up and down in the font column and you will see that some are in bold print. These fonts only contain bold characters. For this example select Verdana, leave the Font Style as Regular, and set the Size to 10. Select Ok to close the dialog box.
Note:
The value of 10 in the Font dialog box refers to a height of 10 points. There are 72 points in an inch so half an inch is 36 points and 18 points is a quarter of an inch. This is a recurring measure for different properties and controls. We were not given the opportunity to change the color of the font in the dialog box. That is actually the ForeColor property. Select the ForeColor property. Notice the down arrow at the right end of the row. The down arrow indicates there is a list of choices for that property. Select the down arrow. There are actually three lists available for the ForeColor property. The default list is the System list. This System list is tied to the Windows settings for each computer and this can make it a bit tricky. We cannot control how the user has set their system colors in Windows and if you're not careful you can set the ForeColor to the same color as the page. If the user has their background set to black and your ForeColor is set to black they will not be able to see the text. The middle list is titled Web. It is a limited list of colors intended to accommodate some of the older browsers that could not display the full complement of colors available today.
Page 28 Chapter 2
The leftmost tab is titled Custom. There are several rows and columns of colors offered with some white or blank cells at the bottom. If the color you want is not there you can right-click on one of the blank cells and a dialog box appears. Here you can select a color form the gradient window or enter the Red, Green, Blue (RGB) values in the boxes provided. If you Google "rgb cobalt blue" you will find several sites that define the color with its RGB values. Cobalt blue's values are Red: 0, Green: 71, and Blue 171. Let's enter those values in the boxes provided and select the Add Color button.
Added Color
Notice that next to the ForeColor property the value is shown as 0, 71, 171. We could have simply typed in the RGB value here separated by commas.
Note: How many colors are available on today's typical computer? There are 256 shades of red, 256 shades of green, and 256 shades of blue. Thus: Red 256 Green 256 Blue 256 Total Colors 16,777,216
Page 29 Chapter 2
Let's see how our text appears with our new settings. Put a Label control near the top of the form. Notice that the color of the text is now blue cobalt blue.
Return to the Properties window. The box just below the Properties window title bar now says, "Label 1 System.Windows.Forms.Label". That's because the label is the currently select control. We can tell visually because Label1 has its grip showing and a dotted lined box around it. The Properties window now shows only those properties associated with Label1. Set the following properties for Label1: Property Name Font Size Bold Text Value lblTitle 12 True Setting Properties
Page 30 Chapter 2
Notice what happened to the label. The text was replaced but it was also extended in size from left to right. Labels have a unique property called AutoSize that allows the label to change size based on the text it contains in the Text property. AutoSize can be turned off in the Properties window either by double-clicking on the word AutoSize, by picking AutoSize then the down arrow and selecting False, or by picking AutoSize and typing in False. When AutoSize is disabled, labels are sized like buttons and other controls. Go ahead and set the AutoSize property to False for lblTitle then use the grips to resize the control.
Let's go back to the form for a moment. Go to the window just below the Properties title bar. Select the down arrow on the right and select frmSettingProperties. Another method is the single-click on the form itself; either makes the form the currently selected object or we say it has the focus. In the Properties window, with the form having the focus, select the BackColor property. Select the lightest yellow in the Custom tab. That gives the program a subtle but colorful appearance.
Run the program (F5 or the green triangle). Where did the form appear on the screen? Is that where you wanted it? Maybe but not likely.
Page 31 Chapter 2
Stop the program by either picking the red X in the upper right corner of the form or the blue square next to the green arrow icon. Scroll down in the Properties window until you see the StartPosition property. For now just set it to CenterScreen and run it again. That looks better. That's enough on properties for now. We'll see how to set properties on numerous controls as we move forward. Stop the program and save your work.
Page 32 Chapter 2
Summary
Concepts
The value we assign to properties allows us to change the appearance and the behavior of the form and controls. There are several ways to change the values in the properties.
Vocabulary
AutoSize
- A property unique to certain controls. When enabled it allows the Label, RadioButton, control to adjust its size automatically. When disabled the size of the box must be set manually. The default setting is Enabled.
Ellipsis - Three periods in a row () when seen in a menu or property button indicates there is
a dialog box style menu that will be displayed if selected.
Form1 in the text property is the default name that is displayed on the form's title bar. Form1
is the default name of the form object in the Design View that holds the controls imported from the Toolbox.
Form1.vb is the default name of the file on the disk that stores the image of the form and its
related code and data.
Focus - An object that is currently selected or highlighted is said to have the focus. ForeColor - The property that controls the color of text. Hungarian Notation - A three letter prefix that identifies the type of an object; lbl for Label,
frm for Form. See the appendix on Hungarian Notation.
Page 33 Chapter 2
Property
- A value that can be set to control the appearance and behavior of a control or object. The background color (BackColor) of a form is an example. The color is the property of the form.
RGB - Stands for Red, Green, Blue; the three base colors of a computer display.
shades of red, 256 of green, and 256 of blue. The possible combinations yield a total of over 16 million colors. (256 x 256 x 256 = 16,777,216)
Chapter Project
Create this form and set the properties to produce a similar appearance. The form should be 800x600 and display in the center of the screen when the program runs. Use the picture of any plant you choose. See if you can figure out how to center the picture in the PictureBox. The drop down box is a ComboBox and the entries are entered in the Items property. When inserting a picture, examine the effect of the SizeMode property.
Page 34 Chapter 3
Before We Start
Let's change some of the settings in our text editor so it's a little easier to see and to add line numbers to our code for easy reference. 1. 2. 3. 4. 5. 6. 7. 8. Go to the pull-down menu of Tools Select "Options" In the lower left corner pick the check box next to "Show all settings". Select "Fonts and Colors". Select the down-arrow under Font. Notice that some fonts are bold in the list. These are monospaced fonts. Select the Consolas font. Change the font size to 12.
Page 35 Chapter 3
9. Scroll down until you see Text Editor. 10. Pick the arrow (triangle) next to Text Editor. 11. Select "All Languages". 12. Select the check box next to "Line numbers". 13. Pick the OK button.
Page 36 Chapter 3
When you get to the Code View take just a moment to examine what's there. At the top of the code window it says:
End Class
This is defining the beginning and the end of where code can be entered for our form. The term Public is called an Access Modifier and it just stipulates that any other part of the program can access or use this form Class.
Page 37 Chapter 3
Note: A Class contains and isolates a section of a program so it can be called whenever and as many times as needed. It works much like a template. We'll learn more about classes later but for now just think of this as the start and the end of the form's code container. Between the start and end of the form class is a line that starts with:
End Sub
That is a subroutine; a small part of the program that runs when btnGold is clicked. The
Private keyword
is another access modifier which simply means that only code within the
frmButton2ColorForm can run or access this subroutine. The fun part of this is that between the Sub and End Sub is where we put the code that we want to run when the user picks the Gold button. So let's think for a moment of the things we've seen so far and reason our way through the process. We won't always get to do this in our examples so it's important to see and understand how it works. Here are some of the things we know: 1. Property values can be changed to change the appearance and behavior of an object or control. 2. We learned about the ForeColor property changing the color of text so what changes the color of the form? If we look back at the Properties window in the Design View, the form has a property called BackColor short for 'background color'. Let's try it, set the form's BackColor property to Green. We can see that yes, that's the property we want to change. You can leave it Green if you want to for now.
Page 38 Chapter 3
Note:
There are three easy ways to go back and forth from the Design View to the Code View. 1. There are two tabs at the top of the main work area. They both have the same name but one has [Design] in the title. 2. Another way is to right-click on the form or inside the Solution Explorer. The context menu offers a selection to get back to the other. 3. The third way is to press F7 to get to the Code View or Shift F7 to get to the Design View.
In the btnGold subroutine start type "me.". When you do, a small menu pops up. This is called
IntelliSense.
It is so cool and so powerful you won't believe how easy it makes programming. The IntelliSense displays the most common things you can do in that location in the code. Now type a "ba". Look at that. BackColor shows up and is highlighted in the list because it is the first entry that begins with 'ba'. Think that's cool? Try pressing the Tab key. IntelliSense not only showed us the properties but it then finished typing it in for us and automatically capitalized the text according to VB standards. That's pretty cool. Alright now we want to set the BackColor property equal to a new value so what are the chances an equal sign will work here. Type it in and see. Wow. Not only did the equal sign work but IntelliSense is now showing us a list of all the colors it can display. Scroll down the list or type 'color.g' if you're a fast touch typist and look what shows up. Third 'g' down in the list is gold. Now you've got to admit that's very cool. Not only does IntelliSense offer the properties we want to change but it also offers us a list of the most common values available.
Page 39 Chapter 3
Run the program (F5) and press the Gold button. The background color of the form changes to gold. Stop the program.
Now let's say we want a different shade of gold. We might Google "RBG gold" and find the shade we want and it turns out to be called Old Gold with an RGB value of 207,181,59. Go back to the code view of our program (F7). Erase the code after the equal sign and type "color.rgb". That would have made sense but it is actually "Color.FromArgb" which stands for
Alpha Red Green Blue (Alpha controls the opacity; later section).
So after the equal sign type color.fromargb(207,181,59). Run the program and pick the Gold button. You might deduce from this example, and rightly so, that you can use any of the computer's 16.8 million colors available in your programs.
Me.BackColor = Color.Gold
or
BackColor = Color.Gold
BackColor is a property contained in almost any control. We can set colors and other properties
Design Time, or we properties of any control when the program is running, which is called Run Time.
when we are designing the UI, which is referred to as Save and close the current project.
Syntax
Page 40 Chapter 3
There is a format to the instructions we wrote in our subroutine. The rules pertaining to that format are called the syntax of the Visual Basic language. The syntax for the instruction we wrote is fairly easy to follow. This is called an
assignment
statement.
We are assigning a value to a variable. The variable in this case is named BackColor and it is a property of the form. Let's look at the first instruction we used to set the background color to gold.
Me.BackColor = Color.Gold
The general syntax or the format of an assignment statement is: Variable = Value Where the variable is on the left of the equal sign and the value it is being assigned is on the right. Visual Basic is an object-oriented programming (OOP) language so in OOP terms the syntax is: Object.Property = Value In our previous instruction "Me." is the object, BackColor is the property, and Color.Gold is the value. The period that separates the various components of a statement is called a such as the Object.Property; read by programmers as Object dot Property.
dot operator
You'll get a complete description and definition of object-oriented programming terms in a later chapter.
Page 41 Chapter 3
Modification
To help clarify the Obect.Property concept let's make a slight modification to our code. Rewrite the statement in the subroutine to read:
btnGold.BackColor = Color.Gold
Now run the program and select the Gold button. In this example the syntax of Object.Property is still the same but now the object is the button itself. Buttons have a BackColor property too.
More Properties
Let's try another example using properties. In this example we will see how to set some of the other properties at design time and change property values at run time.
Page 42 Chapter 3
Page 43 Chapter 3
When the program starts we see that it did not start in the center of the screen so we can set the form's StartPosition to CenterScreen. Stop the program, change the setting, and run the program again. While the program is running, place the cursor at the bottom right corner of the running form. You should see a diagonal bidirectional arrow. Hold down the mouse button and drag the corner so the form expands and shrinks. Notice the effect on the button and the text box. The button moves as the size of the form changes. The text box doesn't move but its width changes. The controls are tied or bound to the edges of the form specified in the Anchor property.
Our one label and button each have a Text property. We can change the properties at run time with an assignment statement for each. Place the cursor on line 4 of the code. If we use the Me object it will invoke IntelliSense but remember that in VB 2010 Me is optional so if we want to use IntelliSense we can hold down the Ctrl key and press the spacebar or just start typing the name of the object you want to use.
Page 44 Chapter 3
Do we need IntelliSense? There are two main advantages of using IntelliSense; it eliminates misspellings and it helps us remember the names we gave our objects and properties. Start typing lbl. As soon as lblName appears, enter a period. IntelliSense will usually go to the Text property because it is the most commonly used. Since the Text property is selected, all you have to do is enter an equal sign. The Text property will now be added along with the equal sign. IntelliSense will continue to offer us options but what we want now is the text for our greeting. There is no predesignated greeting so we have to define the message ourselves. The computer sees text as a string of characters so in programming we simply refer to text as a
string.
For our greeting message we will assign one string to the Text property of our label, lblName. Let's say, "Greetings to our new friend ".
Notice the extra space after friend and that there is no period within the quotation marks. This is only part of our greeting. We are going to add the user's name just as they entered it in the TextBox so we will need the space between our string and the name. We can add the string and the user's name together by entering a plus sign after the right quotation marks. So how do we get the user's name? We've seen that we can assign a value to a property, now we want to get a property to use for the value we want to use in our assignment statement. IntelliSense popped up when we entered the plus sign so we just need to find the right object then its property. We named the TextBox txtName so just type in "tx" and you'll see that txtName is the only object with the txt prefix. To actually get the name from txtName we have to identify the property that currently holds the user's name as its value. That is the Text property so complete the statement by entering a period, the dot separator, then type "te" for Text and hit the Tab key to complete the entry of Text. Your code view should now look like this:
Page 45 Chapter 3
Now run your program to see if it works. When the program displays on the screen the cursor is blinking in the TextBox. This indicates the TextBox has the focus so the user can just start typing their name as instructed by the Text in lblName. Once the user enters their name they can press the button marked Greetings. Notice what happens when they pick the button. The lblName.Text changes to include our message string and the user's name. The window may need to be resized to see the message and the name together. We can either let the user resize the window or since we see this is not the perfect solution we should just change the size of the window in the Design View. If the labels AutoSize property is set to True, the label will expand automatically.
Somewhere along the line someone decided that using the plus sign to add strings together looked too mathematical so they decided to use the ampersand (&) instead but since there were so many programs already written using the plus sign, use of the plus sign could not be removed or replaced. Consequently we can now use either the plus sign or the ampersand. Current industry practices dictate the use of the ampersand. The process of combining strings of text as we did is called concatenation. Multiple strings can be added together to create really long strings. A single string can hold up to 2 billion characters. There were two types of strings used in our example. One came from a property which can change as the program runs. The other is called a
Technically speaking
a literal is any value the computer forgets once it's been used. In our example, there is no way to recall the value placed in quotes though we can easily recall the value in the Text property of txtName anytime and as often as we need it.
MessageBox
Another and more practical method for displaying our greeting is to use another built-in VB class called a MessageBox. Let's see how we can use the MessageBox.
Page 46 Chapter 3
Instead of deleting the line of code we created on line 4 let's just make it inactive but leave it so we can remember what we did. To make the line inactive we can go to the beginning of the line and either type "rem", which will convert to REM. REM is short for "Remark". The REM statement converts everything on the line that follows to a comment meaning it's just text that's there as a note to remind or inform us of something. The shortcut for REM is a single apostrophe ('). Let's place an apostrophe at the very beginning of line 4.
Notice that all of the text in line 4 turned green. This is to indicate that this line is a comment and will be ignored by the program at run time. To add a MessageBox, go to the beginning of line 4, in front of the apostrophe and hit Enter a couple of times to give us some space and make our code easier to read. Move the cursor to line 4 and type MessageBox.Show. You can use IntelliSense though many touch typists prefer to just keep typing. MessageBox is the name of the class and Show is the name of the action or method we want the MessageBox to use. After MessageBox.Show enter and an open parenthesis "(". Once again IntelliSense comes to our aid. Look at the bold letters that say, "text As String". This is the place we can enter our string so after the open parenthesis type, "Greetings to our new friend " & txtName.Text)". Don't forget the closing parenthesis.
Run your program, type in a name, and click on the Greetings button.
A message box pops up that contains our text. That's a very useful function. Look closely at the text in the message box. It says exactly what we specified but notice there is no period. VB's smart but it doesn't automatically add punctuation. What have we seen that we can use to fix that? How about concatenation? We'll just all a period to the end of our text.
Page 47 Chapter 3
Page 48 Chapter 3
Summary
Concepts
We covered a good bit of territory in this section. The order of tasks to develop a program is: 1. Create the interface 2. Set the properties 3. and write the code. We saw how and where to set some of the defaults for Visual Basic by going to the pull-down menu of Tools and selecting Options. We discovered that if we double-click on a control such as a button, VB will take us to the Code View and create the skeleton of a subroutine for us. The assignment statement is used to give or change the value of a property. IntelliSense helps us write our code by offering us the known items that are available at any given part of a statement. A string is a string of text characters that can be added to or concatenated with other strings. A single string can contain up to 2 billion characters. A literal is a fixed value that the computer forgets once it's used. MessageBoxes provide a convenient popup for communicating with the user. A little whitespace or a well placed blank line can make our code a easier to read.
Page 49 Chapter 3
Syntax
The general form of an assignment statement is: Variable = Value MessageBox.Show("Place your text here " & "here" & "here" & "here") The format of entering object-oriented programming (OOP) components is: Object.Property or Object.Method
Vocabulary
Access Modifier - determines what parts of a program can use or access the current section of the code. Types of access modifier include: 1. Public makes a section of code are accessible from anywhere in the project. 2. Private means that a section of code is only accessible within the same class or module. 3. More to come Alpha - The alpha setting controls the opacity of a color.
Ampersand (&) - Concatenates, or joins, two strings.
Apostrophe (') - Shorthand for REM which comments out the code that follows on this line. Assignment statement - assigns a value to a variable. The variable must be to the left of the equal sign and the value being assigned to the variable is to the right of the equal sign. Concatenation - Combining two or more strings to produce a single string. Design Time - Activities conducted to control a program when the program is not running.
Page 50 Chapter 3
Dot operator (.) - A period used as a separator between objects, properties, and methods. Example: btnGold.BackColor = Color.Gold IntelliSense - Microsoft's implementation of code autocompletion. Keyword - A word in Visual Basic that is used in syntax. Keywords are reserved and cannot be used as names for variables, parameters, or procedures.
Literal - A fixed value defined for specific use that cannot be recalled after it has been used. Me - An optional keyword for referencing the use of the current form in code. Monospaced - The description of a font style where all characters have exactly the same width so they are positioned one exactly over another in columns. Therefore an "i" and a "W" have the same width in a monospaced font style. Monospaced fonts are often used in long lists.
Private - An access modifier that restricts access of a code element so that it can only be used by other code in the same class or module. REM - Short for "REMark" which makes all text to the right of REM a comment meaning it is ignored by the program when it runs. Run Time - The time when a program is running. If a value is changed while a program is running we say it is a run time setting.
Statement - A single complete computer instruction.
String - A series of characters assembled (strung together) to create text in the computer. A single string can contain up to 2 billion text characters.
Subroutine - Instructions separated from the rest of the code intended to be run as a group.
Page 51 Chapter 3
Chapter Project
Create a program that concatenates text and displays it in a message box. The program should allow the user to enter their first, middle, and last names in separate text boxes. Each text box should be preceded by a label describing the purpose of the text box. When the message box is displayed the background of the form should change color. If the window is resized at run time the text boxes and button should move with the bottom and right edges of the form. The end result should be similar to:
Hint!
To add space between groups of text concatenate spaces in double quotation marks: MessageBox.Show("My message" & " " & "Another message" & " " & "Message") To make the message break to the next line concatenate a Visual Basic Carriage Return and Line Feed: MessageBox.Show("Message" & vbCrLf & "Message" & vbCrlf & "Message") This would produce the following results:
Page 52 Chapter 4
Chapter 4 Events
What is an Event?
The graphic user interface is one of the most obvious advantages to Visual Basic because of its visual nature. It's right there in front of you. Another major feature of VB is that of events. Events are just as important if not more so but they are not as visual so they dont get as much consideration as the visual components. Consequently, events don't always get the credit or the study they deserve. Visual Basic is called an event-driven programming language because it responds to events. The dictionary defines an event as something that happens at a given place and time. Microsoft defines an event as, "a message sent by an object announcing that something has happened". Pressing a button, selecting a menu item, and reaching a predesignated time on a timer or clock are all examples of events that Visual Basic can sense. There are numerous events in VB and we can write code to respond to events.
Previously we created the skeleton of a subroutine by double-clicking a button. This time we will start with the form. Double-click on the form. When you do a new subroutine is created for you called frmMultipleEvents_Load. This is the Load event of the form meaning that anything we place in this subroutine will be executed when the form loads.
Page 53 Chapter 4
Enter BackColor = Color.Gold and run the program. When the program runs it loads the form. The Load event of the form is fired and the code inside the subroutine is executed.
Page 54 Chapter 4
Default Events
When we double-clicked on the form and previously on a button, Visual Basic automatically chose the event to use when creating the skeleton subroutine. For the form it was the Load event and for a button it was the Click event. Those are the defaults. The most commonly used events for a control is preset as its default. That only makes sense but it's just another way Microsoft has accurately determined what will help us the most. We don't have to use the defaults. We can choose from a list of events for any of our controls.
Select the down arrow next to General and look at the entry with the lightning bolt on the left. The lightning bolt signifies that this is where we select the events or actions for the form object, frmMultipleEvents. Now select the right down arrow next to Load. This is the list of the events built into the form object. The list is so long that it requires a scrollbar to see the complete list. When you scroll up and down you'll notice that the Load event is highlighted meaning this one has been used. Scroll up to and select the Click event. What? The form has a Click event? Well let's see if it's the same as a button's click event. When you selected the form's Click event, Visual Basic creates a new code snippet for the frmMultipleEvents_Click subroutine.
Page 55 Chapter 4
As you may have expected, the form responded to the newly created event. This is going to unlock significant power for us as programmers. Clicking it again does not change it back. We didn't write any code for that.
Page 56 Chapter 4
Is There More?
There are a number or ways we can use events. To see how it works, add three buttons to the form with the following properties: Control Button1 Button2 Button3 Property Name Text Name Text Name Text Value btnRed Red btnYellow Yellow btnExit E&xit
Once the properties are set double-click on each of the buttons to create their code snippets. Go to the Code View. Your code should look something like this:
We can actually cut and paste the existing code from the form load and form click events to their respective button click events. In the btnExit_Click subroutine type Application.Exit. Your code window should now look something like this:
Page 57 Chapter 4
Now run the program. When the program first starts the background will be yellow because the form load event fired as the form loaded. If you pick the button marked Red the form will turn red because the button's click event fired. Pick the yellow button to set it back to yellow. Click on the form when it's yellow and the form will turn red because the form's click event was executed. In the coming examples you will see many occasions where two or more controls need to run the same code. We could always just copy and paste code from one subroutine to another but that can be tedious and it opens the door to errors. There is a simple way to place the code in one place and give access to all of the controls that need it.
Getting Acquainted with Visual Basic Events Let's take a look at modifications to the existing code.
Page 58 Chapter 4
An event is actually controlled or handled by the piece of the instruction that follows the closing parenthesis in the subroutine's opening statement. So for example in line 3 the part that says Me.Click is handling the form's Click event and in line 7 the MyBase.Load is handling the form's Load event. All we have to do is extend the opening line of a subroutine that has the same instruction by adding a comma at the end of the statement and then adding the that should run the same code.
Object.Event
For example: The Me.Click event at the end of line 3 can be added to the end of line 11, continued on line 12 here, and separated with a comma. Line 11 (and 12) would then be: Line
continuation character.
And whatever code exists in the subroutine will now be handled for either event. The frmMultipleEvents_Click and frmMultipleEvents_Load subroutines can actually be deleted; they are no longer needed (I just commented them out so we could still see and study them).
Page 59 Chapter 4
The following code has been modified for the sake of legibility. Notice the use of line continuation characters and the addition of blank lines to improve readability.
Page 60 Chapter 4
Note:
2010 has implicit line continuation characters so there are places where VB knows the line is continued on the next line if you just hit Enter and keep typing then there are places that still require an underscore (_). The following is Microsoft's list of places where an implied line continuation character is accepted: After a comma. After and open parenthesis and before a closing parenthesis. After and open curly brace "{" and before a closing curly brace "}". After an ampersand "&" used in concatenation. After assignment operators such as an equal sign. After binary operators such as +, -, /, and *. It doesnt work on Handles. Handles still requires the "_"/underscore. There are several more that will be discussed when we come to them.
Page 61 Chapter 4
Other Events
Let's look at some other examples of events and while we're at it we'll examine a few more properties. In the Design View, enlarge the form and add a TextBox, a button, and two labels and make the form look similar to this:
Set the following properties: Control TextBox Button1 Label1 Label2 Property Name Name Text Name Text Name Text Value txtName btnReturn Ru&turn lblName Name: lblCurrentLocation Current Location:
Page 62 Chapter 4
Let's start with the code for the TextBox. Go to the Code View, select the left down arrow above the code to see the available objects, and select txtName. Select the right down arrow to see the events available to txtName and select TextChanged. Now that was really an unnecessary step but I wanted you to reinforce the concept of selecting the objects and their events. However, since we really just want to add the object and event to the btnRed_Click subroutine, all we had to do was go to the end of the first line of the subroutine, the signature, and add: txtName.TextChanged. IntelliSense will help you with the options as you type. So you can erase the subroutine for txtName_TextChanged because we've added it to the red button's sub.
Signature
Private Sub btnRed_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btnRed.Click, Me.Click, txtName.TextChanged BackColor = Color.Red End Sub
Go ahead run it. I know you're dying to check it. Yes, as soon as the text in the TextBox changes, the TextChanged event fires so in this case it invoked the btnRed_Click event. That may not seem to have much purpose but the point is to make is visual so you could immediately see the effect. You'll find a lot of uses for the TextChanged event in your programs. Go to the Design View and double-click the Return button. We will use the return button to return some of the properties to the original state. Under the btnReturn signature, type BackColor = Color.LightGray then Enter. Type txtName.Text = Nothing. Your code should look like:
Private Sub btnReturn_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btnReturn.Click BackColor = Color.LightGray txtName.Text = Nothing End Sub
Run the program and type your name in the text box. The background color turns red because of the TextChanged property. Now pick the Return button. Hmmm the form is still red but we programmed it to turn to a light gray.
Page 63 Chapter 4
This is the result of a logic error. The syntax is correct but we've got something in the wrong order. The program changed the background color to light gray but it ran the next instruction so fast it didn't get a chance to display it on the screen. It's that next line that got us. When we set txtName.Text to Nothing we changed the text which fired the TextChanged event so the background color went immediately back to red. Reverse the order of the two instructions in the btnReturn subroutine. From: To:
Try it again. Run the program, type in your name, and pick the Return button. The form is now light gray we fixed our logic error. See the difference in the code? Logic errors can be the most difficult to find. The remaining component in this project is the Current Location label. In this label we want to display the current X and Y coordinates of the cursor. Go to the Code View, select the left down arrow, and select frmMultipleEvents ojbect. Select the right down arrow and select the MouseMove method. Enter the following statement:
lblCurrentLocation.Text = CStr(e.X)
There are a couple of new things going on here. The first is the CStr method. CStr is required because we're using a variable "e" that is actually a number but we need to convert it to text to accommodate the label's Text property. This is actually a holdover from VB6. The variable "e" is provided in the subroutine's signature. If you look at the other signatures you'll see that they all have a variable "e" declared as a System.EventArgs. EventArgs are an object and "e" is a parameter or property of EventArgs. We'll talk more about objects in the future but for now we just need to know that "e" can contain different values for different subs based on the function of the sub. It's built-in feature you'll find very useful. The value of "e" is read only meaning that we can get its current value but we cannot change its value. Run the program and move your mouse around on the form. The value changes as long as the mouse is moving on the form but if the mouse moves off of the form the value stays the same. MouseMove can only see the mouse's location when it's on the form. Let's make the current location lable a little more useful for our users. Change the existing line of code to:
lblCurrentLocation.Text= "X: " & CStr(e.X) & " , " & "Y: " & CStr(e.Y)
Page 64 Chapter 4
Run the program again and move your mouse. Pretty cool? I thought you might like that. You can save and close your project.
Page 65 Chapter 4
Summary
Concepts
We covered a lot of ground in this chapter on events. First and foremost we discovered the power and importance of events. Events are at the core of control in our programs and cannot be taken for granted. We got to see the difference between default and selected events and how to get one subroutine to handle multiple events. The implicit line continuation feature was introduced so we could enhance the appearance and readability of our code. We learned that the first line of a subroutine is called its signature.
Syntax
A single subroutine can handle multiple events simply by adding the a comma and the event to the end of the signature in the general form of Object.Event:
Private Sub btnRed_Click( ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles btnRed.Click, Me.Click, txtName.TextChanged BackColor = Color.Red End Sub
Two added events.
Page 66 Chapter 4
Vocabulary
CStr - converts a numeric value to text or a string value. (Detailed in a later chapter.) e - A parameter of the EventArgs property found in the signature of most event subroutines. event - an action that occurs in the course of a running program such as picking a button, changing text, reaching a preset time, or moving the mouse. event-driven programming - a programming paradigm where the flow of the program is initiated and controlled by events. Object.Event - the general format for specifying an event. The object must be specified first, separated with the dot separator, and then the event or method is specified.
Page 67 Chapter 4
Chapter Project
Create a program that contains three sets of labels with text boxes. The sets should be aligned one over the other. The first label and text box should be for the user to enter their name, the second for their phone number, and the third for city. When the first text box is receiving text the form background color should be red. When the user enters their phone number the background color should turn to yellow. When the user adds text to the third box the background color should be green. If the user changes text in the text box for their name the text in the other two text boxes should be deleted and the screen background color should go to red. Add four buttons that control the height and width of the form so when selected one button makes the screen get 10 pixels wider, another button makes it shorter, and one each for the height and width. Add a new event to the previous four buttons. Use the MouseEnter event so that merely moving the mouse into one of the sizing buttons will change the size of the form. Add another button; the Run button. When selected, the Run button should display a message box with the user's name, phone number, and city entered in the text boxes. The message box should contain a welcoming message and the user's information all on separate lines. There should also be a caption on the title bar of the message box. Add two more buttons; one that turns on the display of the current cursor coordinates and one that makes the coordinate readout disappear so that the user may choose whether to display them or not. Only one of the two buttons should be visible at a time. The last button is the Exit button. It and the Run button should be located in the lower right corner of the form. When the form is resized the Run and Exit buttons should move according to the height and width of the form. Upon completing this project, see what you can add to improve its look and functionality without changing the purpose or scope of the project.
Project
Occasionally there are a few simple things I'd like to interject that are not worthy of a full chapter so I'll just slip them in when I it seems logical to me as a programmer and I think it will be useful to you in the learning process. For example, we have seen several things that we set each time we start a new project so I want to introduce the concept of Project Templates to make things easier for you but also to illustrate Templates as a technique of helping you become more efficient in practice.
Startup Project
In previous examples we've started projects, added controls to the form, set some properties, and written some code for components we'd like to use in every project. If we want the form's background color and title to look the same way every time we start a new project for our company we would like to start future projects with those items used repeatedly to be preset. Let's do that to see how it works. 1. Start a new Windows Forms Application and name it MyProjectTemplate. 2. Change Form1.vb to MainForm.vb. 3. Select the form in Design View. 4. Change its Name property from MainForm to frmMainForm. 5. Change the form's Text Property to Main Form. 6. Change the form's BackColor property to 244, 230, 168; eye-saver buff. 7. Set the form's FontName to Verdana and FontSize to 10. 8. If you have an icon of your company's logo or just a favorite icon add it now. 9. Set the form Size property to 700,500. 10. Set the form's StartPosition property to CenterScreen. 11. Add a label. 12. Set the label's Name property to lblCompanyName 13. Set the form's FontSize to 17 and Bold to True. 14. Set the label's ForeColor to Maroon.
15. Set the Label's Text property to VB Productions, LLC. 16. Move the label near the top of the form until the distance snap-line appears. 17. Select the label and use the Format menu to center the label Horizontally. 18. Set the label's Anchor property to Top. 19. Add two buttons. 20. Rename Button1 to btnExit. 21. Set its Text property to E&xit. 22. Move the Exit button to the lower right corner of the form. 23. Rename Button2 to btnRun. 24. Set its Text property to &Run. 25. Align the Run button with the Exit button. 26. Set the Anchor property for both buttons to Bottom, Right. 27. Double-click on the Exit button. 28. Type Application.Exit in the stub. 29. Run the program to test for errors. Wow. That was a lot of work and we haven't even thought about what this program is going to do. That's why we need a template. Go to the pull-down menu of File and Select Export Template. On the Export Template select Project template then Next. Give the Template a name such as VB Productions and a Template description. You may add an icon but it should be a 32x32 pixel icon. Select Finish. Now start a new project. This time select Visual Basic under Installed Templates. Scroll down until you see your template, select it, and voil. You have saved all that work each time you create a new project. You can modify and resave your template anytime you like but keep in mind that templates only apply to new projects. Templates will not retroactively update projects created prior to the modifications. So that's a Quick Topic Insert. Hope you've enjoyed and more importantly I hope it helps you become more productive.
Page 70 Chapter 5
in Visual Basic and use it in a program primarily written in Visual C++ and be guaranteed that the numbers, text, and Boolean types will be calculated and stored the same way and produce the same results. The computer only knows 0 and 1, binary numbers, so all numeric data types are based on a binary system so a byte data type can only have 28 or 256 values. Another slightly counter intuitive concept is that computers start counting at zero so those 256 values are counted from 0 to 255, not 1 to 256.
Page 71 Chapter 5
Data Types
Prefix
dec dbl sng byt int lng shr chr str bln dtm obj
Binary Value
2 1024 2 32 2 8 2 32 2 64 2 16 2 16 2 N/A N/A N/A N/A
96
Numeric Other
Text
* Depends on the platform used. Primitive data types are those that are built into Visual Basic as they existed in versions prior to the development of the .NET Framework.
It dimensions or allocates the amount of memory we need to use this variable. In the this example we are allocating space for a String variable named strFirstName. Let's see how that's used in a program. While we're at it, let's start talking about that getting rich concept discussed in the Introduction. No, I haven't forgotten.
Integer
Float
Page 72 Chapter 5
determine is the type of data we need. Interest rates are decimal values because when we calculate them they are not likely to be a whole number. The previous chart of data types and the Hungarian Notation tables in Appendix A indicate that the prefix for a decimal data type is dec. The name should reflect the purpose of the information it contains; an interest rate. If we name the variable decInterestRate or just decRate, it will be clear in a program designed to calculate interest what information is to be stored in that variable. Let's see an example.
New Program
Let's write a new program that illustrates how to use data types. One of my favorite topics for new users to program is to calculate interest. The formula for calculating simple interest is: I = PRT or Interest = Principal x Rate x Time Our program will provide a place for the user to enter their name, the amount of the principal being invested or borrowed, the interest rate, and the term (or the length of time) of the investment or loan.
Page 73 Chapter 5
TextBox1 TextBox2 TextBox3 TextBox4 Label1 Label2 Label3 Label4 Label5 Label6 Label7 Label8 Button1 Button2
Page 74 Chapter 5
Run your program to test the layout. Use the Tab key to cycle through the controls. Unless you were very lucky the order in which the Tab key moves through the controls is probably not what you would like.
Focus.
TabIndex
control but that could take a long time. A faster way is to use the Tab Order feature. Select the form, go to the pull-down menu of View, and select Tab Order. Blue numbered boxes appear on the controls of the form. The number in box indicates the TabIndex or where each object falls in the order for receiving focus.
Page 75 Chapter 5
Start with the title label and pick each object in succession. For text boxes that have labels, pick the label first then the text box. If a control cannot receive focus, such as a label, the next numbered object receives the focus in its place. Your form with its new tab order should look something like this:
Once you've set the tab order go back to the View menu and select Tab Order. Now run your program and test the tab order. Each control in succession should receive the focus as you press the Tab key. Ok, we've designed the interface and set the properties let's write some code.
Convert
Convert.ToDecimal(txtPrincipal.text) So syntax for converting the Text property to a decimal and assigning it to a variable is:
Page 76 Chapter 5
decPrincipal = Convert.ToDecimal(txtPrincipal.Text)
Let's look at the code.
There as several points to discuss in this small example of code. First, notice the difference between lines 7 and 8. In line 7, the variable is being dimensioned but in line 8 the variable is being dimensioned, the Text property is being converted to a numeric value, and being assigned to the variable as it's being dimensioned. Now look at line 12. Not only did we convert a value but we also performed a calculation on the converted as we assigned it to the variable. In lines 17 and 18 we concatenated the existing Text property with the numeric data after is has been converted back to a string. In line 18 we did the calculation before converting the numeric value to a string. The variables are dimensioned and line 15 uses the converted values to calculate the interest. Look at line 17. We had to convert the calculated numeric value back to text to populate the Text property of the label.
Page 77 Chapter 5
In line 18, we added the value of the interest to the principal to get the total amount invested (or owed) and then converted to a string so we can place the value in the Text property of another label.
Note:
We previously saw a method for converting something to a String in the form of CStr(). This is a holdover from VB6 and earlier but it is still in use. It's better to use the object oriented method for converting values. I occasionally use the older method so you will be familiar with it in case you see it used in existing code. While the Convert Class method is preferred, if there is another way to do something you should know what it is.
The only thing left is to terminate the program. Double-click on the Exit button and in the btnExit_Click event handler type Application.Exit. Run the program, enter data in the text boxes, and hit Calculate. When you and I run the program we get good answers because we know the kind of information the program accepts. The problem is not all users know the rules. What happens if the user enters 2.5 years? Crash! Resolving the previous solution opens a trap door. To allow the user to enter a decimal number we can simply change the variable type. I only mention this due to the number of incidents I've encountered over the years. People will go to the line that says:
Page 78 Chapter 5
numbers and no more than two decimal places or maybe none at all. VB gives us some simple tools for making that work.
Numbers to Strings
In the precious example we used the Convert Class to convert variables from strings to numbers and back. Numeric data types have a conversion method called into their structure for which the syntax is: numValue.ToString Example: decInterest.ToString This syntax allows us to use a method of displaying a string of numbers into a specific format.
lblInterestEarned.Text=decInterest.ToString("f2")
The "f2" specifies that there should be a fixed-point limiting two digits past the decimal and the results would be: 3246.86. Well that's an improvement but let's look at another option. Change the ("f2") to ("n2") so that we have:
lblInterestEarned.Text = decInterest.ToString("n2")
This results in an improved format of: 3,246.86. If we wanted to we could concatenate a dollar sign in front of that but that would override or get in the way of any cultural settings if we wanted to let someone from England run it using the English pound sign. Fortunately VB contains another format type for currency. Change the ("n2") to ("c2") so that the new line becomes:
lblInterestEarned.Text = decInterest.ToString("c2")
Page 79 Chapter 5
The new results are: $3,246.86. That's exactly what we need in our example. The general syntax is: numName.ToString("AX") where A is called the Format Specifier and the X is the number of decimal places to be used. The Format Specifiers that will be used in this text are:
Description
Displays currency WITH group separator (comma) and 2 decimal places. Scientific notation Fixed-point: NO group separator (comma) but sets decimal places. Number with group separator (comma) and 3 decimal places. Percent: Multiplies by 100, includes comma, decimal places, and percent sign (%).
Example/Results
3246.85845 $3,246.86
ToString("e2") ToString("f4")
ToString("n3")
3246.85845 3,246.858
ToString("p3")
3246.85845 324,685.845%
Note: The default number of decimal places is two for all Specifiers except Exponential.
So how do we use Standard Numeric Format Strings in our program? changes. First, let's change line 17 to use the Format String: Let's make a few
Page 80 Chapter 5
We'd like to change line 18 to use Format Strings too but it adds the Interest and Principal in the parenthesis so we have to do something different here. First, let's dimension a new variable to hold the sum of the Principal and Interest; decTotatInvested.
Getting Acquainted with Visual Basic Data Types and Calculations Now let's add the Principal and Interest on a separate line:
Page 81 Chapter 5
Now we can change the penultimate line of the subroutine to use the newly declared variable with the proper Format String:
Getting Acquainted with Visual Basic Data Types and Calculations Run the program and examine the results.
Page 82 Chapter 5
Page 83 Chapter 5
Summary
Concepts
In this chapter we talked about Data Types, how to convert them, how to use Tab Order to control interface flow, and how to format strings to make them display the way we want. We learned how to reserve space in memory for our variables using the Dim statement and though there will always be controversy on the proper way to name variables, we took a brief look at a simple naming convention. The Interest Calculator program was explained not only in detail but as we stepped through the reasoning of changes made to improve the program. Too often tutorials explain how to make changes but not how. Understanding why is as important as understanding how and maybe even more so.
Vocabulary
Common Type System (CTS) - A system for defining data types so they behave and are treated the same across any programming language or hardware that complies with the Common Type System. Convert Class - Converts a base type to another base type such as converting an integer to a decimal. Dim - Short for Dimension, Dim is used to allocate space in memory for variables. Data Types - Computers differentiate between data types such as integer, decimal, and string. Focus - The control that currently contains the cursor or is currently selected to receive input is said to have the focus of the program. Standard Numeric Format Strings - A string that consists of a specific alpha character (Format Specifier) and a numeric value (Precision Specifier) used to control the format of printing numeric types as strings. Example: decSomeNumber.ToString("f3") prints the numeric value in decSomeNumber with fixed at three characters past the decimal point.
Page 84 Chapter 5
Tab Index - The order in which controls are accessed, or receive focus, using the Tab key (or Shift + Tab) is determined by the Tab Index property of each control. Tab Order - A graphical method of setting the Tab Indexes by selecting the controls in the order they are to receive focus. The Tab Order feature is found on the View pull-down menu. ToString - A method built in to the Convert class and numeric data types that converts numeric values to strings.
Syntax
Chapter Project
Write a new program that calculates the time required to travel to each of the planets in the solar system and how much it would cost if your craft ran on gasoline that sells for $3.49 per gallon (high test) and gets 14 miles to the gallon. Display the distance in miles to each planet, the time it would take to get there if you traveled at 186,000 feet per second (the speed of light), and how much it would cost in dollars.
Page 85 Chapter 5
Page 86 Chapter 5
Page 87 Chapter 6
Page 88 Chapter 6
You've learned about data types, calculations, and setting properties but what do you do if don't know a lot about retirement calculations? Google! That's right, you have to figure it out. Now odds are the person who gave you the assignment will probably know enough to at least get you started but that's not always the case and when formulas are involved, the client nor the boss is likely to have them in their head. You're going to have to figure this out on your own and you are responsible for it being right. If you just search for retirement calculations you will start to see terms like "annuity formula", "retirement needs", and you'll find endless links to calculators, planners, and templates. When you start reading you'll learn about the time value of money and interest calculations. It will most likely be left up to you to learn about the mechanics of the process. Let's get organized. We'll use a very simple model developed by the military in World War II; ADDIE 1. 2. 3. 4. 5. Analyze Design Develop Implement Evaluate
We need to analyze the problem and break it down to its smallest and most discrete components. We need to understand the process of working the problem from start to finish. Once we understand the problem we can design a process for working the problem. When we fully understand the process and have designed the solution, and not before, we will then develop the code. Implementation may include alpha testing, at the developer's site, and beta testing, at a sampling of end users' sites. The performance of the software will be evaluated and the process repeated until the program is stable and provides the right answers. ADDIE is just one of the many software development methodologies or models in use today. It's easy to remember and most of the others use the same process but may be stated in greater detail or specific to time and order. The Agile software development method is a more specific model and worth understanding. While not discussed here in detail, the four points of the Agile Manifesto promote concepts that favor more programming and development and it is intended to reduce the tendency to over managing projects. The brevity and clarity of the Agile Manifesto fairly sums up the premise of Agile development.
Getting Acquainted with Visual Basic Data Types and Calculations "We are uncovering better ways of developing software by doing it and helping others do it. Through this work we have come to value:
Page 89 Chapter 6
Individuals and interactions over processes and tools Working software over comprehensive documentation Customer collaboration over contract negotiation Responding to change over following a plan
That is, while there is value in the items to the right, we value the items on the left more." Agile Manifesto February 2001 Over management can deplete a budget and kill a project.
Our Process
After considerable reading, research, analysis, and manual calculations, we have developed our process that consists of five steps to solving the problem. The nice thing about this particular problem is there are several existing calculators on the web that we can use to check our calculations. That's not always the case. The following five basic steps are required to calculate what it's going to take to make us financially independent.
Step 1
Determine how much is needed to live comfortably. Analyze your spending. List all of your expenses and don't forget those you pay annually such as property taxes, insurance, birthdays, anniversaries, and vacations. The list should be very long if complete. There are numerous examples and spreadsheet templates available on the Internet for personal budgets.
Step 2
Try to determine when you would like to start living the good life; retire. Saving the kind of money needed for this process doesn't happen in a year or two unless you win the lottery or
Page 90 Chapter 6
build a better search engine. Be reasonable and recognize that the calculations will ultimately give us the answer.
Step 3
Determine how much money it will take in the year you want to retire to be equal to the amount of money you said you needed to live in Step1. The difference is called the time value of money. The amount you need to live on today is woefully short of what you will need if you retire 20 years from now. The value of money goes down over time. For this calculation, we can use the simple interest formula we used in the previous chapter to determine how much the value of money will change (the interest is the difference): I=PxRxT Where: I = The interest earned or the change in value P = The amount invested R = The annual interest rate (or inflation rate) T = Time - the number of years to save
Step 4
Calculate how much money you need to have invested so you can live on half of the interest you receive from your investment. Why half the interest? The other half continues to grow enough to cover inflation and with any luck that upgrade. Once we know how much we need to earn in interest, we can again use the simple interest formula but this time, solve for the Principal on which the interest is paid: If: I=PxRxT
Then: P = I RxT
Step 5
Calculate how much money you will have to save each month at a fixed interest rate compounded monthly. This will require the use of the Future Value of an Ordinary Annuity formula: Fv = Pv (1 + i/n)nt
Page 91 Chapter 6
The Calculations
In the previous chapter we created a simple program to calculate simple interest. In this chapter we will develop a more extensive program and we will use the simple interest formula, the compound interest formula, and the future value formula to calculate how much money we need to be financially independent and how much we have to invest to get there. The formula for calculating compound interest is: A = P(1 + r/n)ntWhere: A = The final and total amount P = Principal amount invested r = Annual nominal interest rate as decimal n = Number of times interest is compounded per year t = The number of years invested The compound interest formula is often restated in terms of time that accountants refer to as the time value of money so that the Future Value of the sum is: Fv = Pv (1 + i/n)nt Where: Fv = Future value of investment or payments Pv = Present value of investment or payments i = Interest rate per period n = Number of periods t = Time in years
To find the Present Value the formula can be restructured to: Pv = Fv (1+i/n)nt Using the same variables.
Another formula we'll see in this chapter is called the Future Value of an Ordinary Annuity. An
Fv = Future Value of an Ordinary Annuity PMT = The amount of each payment i = Interest rate per period n = The number of compounding periods
Our Example
Step 1
Page 92 Chapter 6
Let's assume that we've determined we need $70,000 a year to live our desired lifestyle.
Step 2
Let's just say we want to retire in 20 years. We can always change that if we want to retire sooner or if we can't make the investment payments that soon.
Step 3
Use the simple interest formula to calculate how much it will take to be equal to the $70k we specified in Step 1 when we need it in 20 years as specified in Step 2 assuming an annual inflation rate of 4%. buffer. I=PxRxT
Note:
Where: I = Interest; in this case the interest is actually the increase of the cost of living for $70,000 P = The amount you need to live now; $70,000 R = 4% or 0.04 (the rate of inflation in this case) T = 20 years
I = $70,000 x 0.04 x 20 I = $56,000 the change in the value of the money over time. The total amount needed in 20 years to equal $70,000 is: $70,000 + $56,000 = $126,000
Step 4
In Step 4 we need to solve for the Principal that would be required to earn enough interest that half of the interest earned is $126,000. For this example we will use 8% interest earned on our investment so half of the interest would be 4%. Therefore: I=PxRxT
Where: I = The interest needed for one year; $126,000 P = The unknown investment amount R = 4% or 0.04; half of the interest rate for the year T = Time; 1 year $126,000 = P x 0.04 x 1year P = $126,000 / 0.04
Page 93 Chapter 6
P = $3,150,000 invested to yield the $126,000 needed to be equal to the $70,000 we said we needed 20 years from now.
Step 5
Use the Future Value of an Ordinary Annuity formula to calculate how much has to be saved each month to meet the retirement goal; $3,150,000. Continue to use the 8% annual interest rate. The formula is and we want to solve for the Payment, PMT: Fv = PMT ((1 + i)n - 1) i Fv = Future Value of an Ordinary Annuity; $3,150,000 PMT = The amount of each payment i = Interest rate per period; 8%/12 or 0.08/12=0.0067 n = The number of compounding periods; 20x12=240
Therefore: $3,150,000 = PMT ((1 + 0.0067) 240 - 1 .067 PMT = $5,347.86 per month At this point, the user must decide whether or not this is feasible. This would be a real stretch for most people so the question is what can we change to make it doable? We could reevaluate how much we needed to live or the number of years we can work to retirement.
Page 94 Chapter 6
Page 95 Chapter 6
Property
File Name Name Text Icon AcceptButton CancelButton Name Name TextAlign Name TextAlign Name TextAlign Name Name Text Name Text Name Text Name Text Name Text Name Text Name Text Name Text Name Text Anchor Name Text Anchor
Value
RetirementCalculator.vb frmCalculator Retirement Calculator calc.ico btnCalculate btnExit txtName txtPrincipal Right txtRate Right txtTime Right txtPreparedBy lblRetirementCalculator Retirement Planning, Inc lblName Name: lblCurrentCostOfLiving CurrentCostOfLiving(Principal): lblRate Rate: lblTime Time: lblPercentSign % lblYears years lblPreparedBy Prepared By: btnCalculate C&alculate Bottom, Right btnExit E&xit Bottom, Right
TextBox1 TextBox2 TextBox3 TextBox4 TextBox5 lblCompanyName Label1 Label2 Label3 Label4 Label7 Label8 Label9 btnRun
btnExit
Page 96 Chapter 6
We now need a second form. We could just add a new Windows Form but it wouldn't look like or frmRetirementCalculator form. Since we may want to use this form again in the future, let's create a template of just the form. First save all of your files. Then select frmRetirementCalculator to make it active. Go to the pull-down menu of File and select Export Template. On the Choose Template Type window choose Item Template because we don't want the entire project, just the form item. Pick Next. On the Select Item to Export window select RetirementCalculator.vb and pick Next. On the Select Item References window select all of the references. On the Select Template Options window give the form a unique name such as Yellow700x500 or any name of your choosing. Enter something for the description that will remind you of the purpose of this form. It's good to select an icon if you have one handy that might apply to this form. The Preview Image is a place to enter a picture so if you have a screenshot of the form you could place it here. Select Finish. To add the new form to your existing project, right-click on the solution name, select Add, then New Item. That will take you to the list of Installed Templates on the Add New Item window. Locate the template you just created, give it a more meaningful name (RetirementReport.vb for this example), and select Add. The new form will appear in the Solution Explorer.
Getting Acquainted with Visual Basic Data Types and Calculations Add the controls listed to the new form and set the following properties: Control
MainForm.vb frmMainForm
Page 97 Chapter 6
Property
File Name Name Text Icon AcceptButton CancelButton Name Text Name Text Name Text Name Text Name Text Name Text Name Text Name Text Name Text Name Text Anchor Name Text Anchor
Value
RetirementReport.vb frmReport Retirement Report sun.ico btnPrint btnClose lblRetirementCalculator Retirement Planning, Inc lblClientName Prepared for: lblYearsToRetirement Years to Retirement: lblCurrentCostOfLiving Current Cost of Living: lblCostOfLivingAtRetirement Cost of Living at Retirement: lblPrincipalAtRetirement Principal at Retirement: lblMonthlyInvestment Monthly Investment: lblInterestRate Interest Rate: lblPreparedBy Prepared by: btnPrint &Close Bottom, Right btnClose &Close Bottom, Right
lblCompanyName Label1 Label2 Label3 Label4 Label5 Label6 Label7 Label8 btnPrint
btnClose
Note:
All label Text properties that end in a semicolon should also have 2 trailing spaces for
display purposes and so we don't have to concatenate spaces to the names later in code.
Page 98 Chapter 6
Page 99 Chapter 6
It's usually best to code one process at a time, test it, and go to the next. We've designed our interface and set the properties so now we will take on each code section in succession. Let's start with the retirement calculator form. Double-click on the Calculate button. One thing we can do first, just so we can see what we've done so far, is add a statement that will display the second form when the button is selected. Start typing "frm" and IntelliSense shows the two forms in our project. Complete the line so that you have:
This simply displays or shows the Retirement Report form. If you run the program now you will discover that the second form displays. What happens if you select the Close button? Make sure that the code for the close button is simply "Close()" (without the quotes). While we're at it, you might want to check to insure that the code for the Exit button on the calculator form is "Application.Exit" (without the quotes). Stop the program and make sure the Calculator form is visible in the Design View. Double-click the Calculate button on the Retirement Calculator form. That returns us to the code section for the button. Let's follow our process steps. Step 1 asked for the amount of money needed to live today and in our example we said $70,000. Whatever the user enters, we want that value to do two things; become part of our calculation and show up on the report form.
Now do the same for the Rate and Time text boxes. Your code for the Calculator form should now look something like this:
Note: To allow code to display better on the pages I will start using the implicit line continuation which changes the previous code to:
Implicit line continuation was discussed in a previous chapter but I wanted to make sure you are aware of the difference in the format and don't get lost. To be clear: line 9 is actually part of line 8. It is just continued on line 9 to allow it to better fit the page; for this text and if you print out your code.
Test Often
Running the program to make sure everything is working between the addition of each section is a good practice. Otherwise, you may have to deal with multiple errors instead of one at a time.
Note:
This is all one statement but uses the implied line continuation feature right after the
equal sign. Also note that because we added a space after the colons in the label's text property we do not have to concatenate the space between the strings. Using similar syntax add the Years to Retirement and Current Cost of Living values to the Report form.
declared
P = decPrincipal R = Rate of inflation 4% or 0.04 (which is 4 / 100) T = decTime The 4% is the value chosen for inflation in this example. Financial planners tend to use 3-3.5% which is more realistic for most years but 4% is used here to compensate for the possibility of another economic condition similar to the years Jimmy Carter was President or simply as a safety factor.
This is one place you might want to use comments to remind yourself or explain to the members of your team what you're doing in this calculation.
'The formula is I = PRT 'P = The decCurrentCostOfLiving is the Principal. 'R = The decRate is the inflation Rate. 'T = The decTime is the Time until retirement. decCostOfLivingAtRetirement = decPrincipal + (decCurrentCostOfLiving * 4 / 100 * decTime)
Once the value of the Cost of Living at Retirement is calculated it needs to be displayed on the Report form.
'Annual cost of living at retirement = Current Cost of Living 'plus Inflation for 20 years. frmReport.lblCostOfLivingAtRetirement.Text = frmReport.lblCostOfLivingAtRetirement.Text & decCostOfLivingAtRetirement.ToString("c0")
Test Data
If you are testing periodically, you soon discover that you have to enter data every time you run the program. There are a lot of ways to solve that problem but let's use one here that fits what we've learned so far. While in the btnCalculate_Click subroutine in the Code View of the Calculator form, go to the top of the code and click the down arrow next to btnCalculate. Choose (frmCalculator Events). Now select the down arrow next to (Declarations) and scroll down and select Load. Add the following lines:
'The following lines are for temporary test 'data only and should be commented out or 'removed prior to release. txtName.Text = "John Louis Longwood, III" txtPrincipal.Text = "70000" txtRate.Text = "8" txtTime.Text = "20" txtPreparedBy.Text = "Fred McKlanahan" frmReport.btnPrint.Enabled = False 'End of test data.
Now you won't have to fill out the form every time you want to run a test. Just be sure to comment out or remove the lines prior to publication.
Note:
I prefer to move my Load event to the beginning of my code. That way when I come back to it six months from now I can see what happens in the program first: the Form_Load event. It's not a requirement, just a good practice. The next item on the Report form is Principal at Retirement. The Principal at Retirement is how much the client has to have in the bank the day they retire so they can live off half of the interest earned. Remember, the other half of the interest has to be added back to the principal every month to compensate for inflation. Otherwise, the client may outlive their money. This calculation also requires the simple interest formula but this time we have to solve for the Principal. I = PRT so P=I RT I = decCostOfLivingAtRetirement R = decRate / 2 T = 1 year
'The formula is I = PRT 'Solve for Principal at retirement: 'P = I/RT/2 because we're only living on 1/2 the interest. 'Principal at Retirement = ' Cost of Living at Retirement / Rate /2 x Time decPrincipalAtRetirement = decCostOfLivingAtRetirement / (decRate / 2)
To add the value to the Report form:
Getting Acquainted with Visual Basic Data Types and Calculations Run the program. Check your values against the following:
The next calculation is for the amount the user must deposit each month to acquire the amount of the Principal at Retirement in the previous calculation. It sounds like the easiest but the formula is the most complex because interest is applied to the principal each month along with the new deposit. The formula for this is called the Future Value of an Ordinary Annuity. An annuity is a steady stream of money; the monthly deposit. The actual formula is:
Fv = Future Value of an Ordinary Annuity which in our example is decPrincipalAtRetirement PMT = The amount of each payment (the unknown) Must be declared: decMonthlyPayment i = Interest rate per period, there are 12 months or periods so 8% / 12 or 0.08 / 12=0.0067 n = The number of compounding periods; 20x12=240
The formula looks a bit daunting to some but it's really not that bad when you break it down into components and set it up one piece at a time. Start with the innermost parenthesis, (1 + i)n. The "i" is the interest and the "n" is the number of compounding periods. Keep in mind that the user enters the Time in years and our interest is compounded monthly so we have to multiply the years times 12 months per year. For example 20 years compounded monthly is 20 x 12 or 240. We have already declared the interest as decRate so (1 + i)n is ((1 + (decRate/12)). Just keep in mind that everywhere you see 12 it's because we are calculating for 12 months of the year. The rest is fairly straight forward:
'The Monthly Investment is calculated using 'Future Value of an Ordinary Annuity. 'The formula is: F = P(((1 + I)^n - 1)/I) 'Where: 'F = Future Value of an Ordinary Annuity or 'at Retirement 'P = Monthly Payment 'I = Interest Rate per compounding period 'n = The number of compounding periods(# of 'To solve for P: P = F/(((1 + I)^n - 1)/I) decMonthlyPayment = CDec(decPrincipalAtRetirement / (((1 + (decRate / 12)) ^ (decTime * 12)
(decRate / 12))) To display the value on the Report form:
the
Principal
years x 12 months)
- 1) /
After all of that arithmetic, the next two look like child's play. We want to display the interest rate and the name of the preparer on the Report form.
Run your program and check your answers against the following:
To make the report look better, select all of the labels, click on the Cost of Living at Retirement label (because it's the longest), go to Format on the pull-down menus, select Align, and then Rights. With all of the labels still selected, use the right arrow key to move the labels to the right until their right edges are near the center of the form.
By the way, the blue lines on the Report form were created by using the LineShape found in the Visual Basic Power Packs in the Toolbox. This was a good project. Some of the math looked a bit unwieldy but when you break it down you see that it's not that much. At any rate you have certainly earned a break. The code for this project is posted in its entirety at the end of this chapter so if you got lost or have an error you can see it all at once.
Page 115
Notes: Databases
Access