You are on page 1of 96

The Microsoft Visual Basic Environment

Microsoft Visual Basic


Introduction
Microsoft Visual Basic is a development environment used to create programs or applications for the Microsoft Windows family of operating systems. To do this, it uses a computer language that was originally called Basic but has been transformed in an advanced language also called Visual Basic. This language makes it particularly easy to create effective applications because it offers a working tool as a studio equipped with necessary materials to keep you moving. Microsoft Visual Basic ships in three packages and sometimes various formats. The way you launch it depends on how it was installed. We will first analyze the studio and review some of its equipments, and then we will start creating small applications. Starting Microsoft Visual Basic depends on how it was set up on your machine. If it were installed as a stand alone product, it would be available under the Programs menu; otherwise, it might be under the Microsoft Visual Studio group of applications. However it was installed, now is the time to launch it.

Integrated Development Environment (IDE)


1. To launch Visual Basic, on the Taskbar, click Start -> (All) Programs -> Microsoft Visual
Studio 6.0 -> Microsoft Visual Basic 6.0

2. When Microsoft Visual Basic starts, the New Project dialog box comes up:

At this time, we will not go through what all these icons mean. Just make sure that the Standard EXE icon is selected and click Open 3. A typical studio such as the one used by Visual Basic is referred to as an Integrated Development Environment (IDE). As a classic application, Microsoft Visual Basic displays a title bar on top. The title bar is mainly made of three sections. On the most left side, there is the application icon. This icon has a menu of its own. To see the menu, click the small icon and click Maximize (or Restore) 4. On the right side of the application icon, the name of the file allows to identify what you are working on. Microsoft Visual Basic names each one of its applications a project. A Project is a collection of files used to build a particular application. When Visual Basic starts, it calls the first application Project1. When you save a project, you give it an appropriate name, and the name on the title bar gets updated. On the right side of the Project1, the name helps to know what environment you are using to build your application. The Microsoft Visual Basic name is followed by the empty area of the title. This area can be used as a menu to maximize or restore a window. To experiment with it, double-click the empty section of the title bar. Notice that the window has been maximized (or restored) again

5. The last three buttons on the title bar are used to perform windows operations. Every one
of the buttons has a name. To find out a button's name, position your mouse on top of it and a name will appear. To experiment with the buttons, click the Minimize button

6. To bring back Microsoft Visual Basic, on the Task bar, click Project1.

7. Under the title bar, you have a menu made of words such as File, Edit, View, etc. These
allow you to perform almost any kind of operation. To use a menu, you click one of the words. A menu drops down and you make another selection from it. We need to review how a menu functions because as a programmer, you will have to create a menu or menus sooner or later. There are typically four kinds of menus here.

A disabled menu is a menu that is temporarily unavailable. This could be due to anything. For example, it might wait for another action to happen. Sometimes, there might be something running on the background and this would disable a function of your program or the application. To view an example of such menus, on the main menu, click Edit and observe a lot of disabled menus. To see another, position the mouse on Diagram and notice that the whole Diagram menu is disabled.

8.

An enabled menu standing by itself will usually perform a brief action, sometimes leaving the impression that nothing happened. This kind of menu can be used to quickly save a file, display a toolbar, etc. To see an example, on the main menu, click Edit -> Copy. It looks like nothing happened. The form (or if anything else was selected) has been copied to the clipboard, which is a temporary storage area of your computer.

9. To see another kind, on the main menu, click View -> Locals Window. Notice that there is a new section on the screen now.

10.

A menu with three periods () is typically used to launch or open a dialog box. To experiment with it, on the main menu, click Tools -> Options Notice that the Options dialog displays. sheet. From the Code Colors list box, click Normal Text. Click the Foreground combo box and select a green color. From the Code Colors list, click Selection Text. Click the Foreground combo box and select blue. Click the background combo box and select the lime color

11. The Options dialog is made of various property sheets. Click the Editor Format property

12. Click Comment Text. Click the Foreground combo box and select dark gray. Click Keyword Text. From the Foreground combo box, select blue. Click Identifier Text. From the Foreground combo box, select pink. 13. Click OK. At this time, we cannot yet experiment with the new settings.

14.

A menu with an arrow indicates that it has a sub-menu, which is a child menu. To see an example, on the main menu, click View -> Toolbars. Notice the items under the Toolbars menu.

15. To see another menu like that, position the mouse on Format -> Center In Form. 16. Whenever a menu is opened but you don't want to use it, you can dismiss it with the Esc key. To dismiss the current menu, press Esc. Press Esc again. 17. Some menu items present a key or a combination of keys on their line: this is called a shortcut. A shortcut is a key or a combination of keys that allows you or the user to perform an action quicker than using the menu. Some shortcuts can be seen on the menu of Visual Basic. Some other shortcuts are part of Microsoft Windows operating systems. To see a list of some of the shortcuts, on the main menu, click Edit. Observe the list of shortcuts and the actions they are associated with.

18. Press Esc to dismiss the menu.


19. To use a one-key shortcut, just press the corresponding key. For example, press F5. Notice that the form changes its looks. Actually the form went from its design state to its running state.

20. To close the running form, click its close button

21. To use a combination of keys, press the first key (or one of the keys), and then press the other or others. Finally release the keys. To experiment with other shortcuts, press and hold Ctrl, then press F5. Notice that the form runs again as an application.

22. To close the running form, since it is treated as a complete application, press Alt + F4.
Some other shortcuts are part of the operating system. For example, Ctrl + Esc would open the Start menu; Alt + F4 is used to close applications.

23. Under the menu, there is a toolbar. This first toolbar is called the Standard toolbar.
The Standard toolbar allows you to perform many of the most common actions that would require the main menu, except that the toolbar is handier and closer to the user, which makes it faster. A toolbar is made of buttons that you click to perform the corresponding action. At first, nothing is obvious with these buttons. Therefore, to find out what a particular button is used for, position your mouse on top of it and keep it there for 2 seconds. A word and group of word will appear: this is the tool tip, allowing you to identify the button. The buttons are usually named after their tool tip. To get acquainted with some of the buttons, position your mouse on the first button for 1 or 2 seconds and observe the tool tip.

24. Move the mouse to another button and read the tool tip.

25. To experiment with one of the button, on the Standard toolbar, click the Start button
Notice that the form runs in its execution state.

26. To stop the running form, on the Standard toolbar, click the End button

27. Some of the buttons on the toolbar have an arrow on them. This indicates that the button, behaving like a menu or a combo box, can display more items when you click its arrow. To see an example, click the arrow of the Add Form button. Notice other items available. 28. Without clicking, move the mouse to the arrow of the first button on the toolbar, the Add Standard EXE Project button. 29. To dismiss the menu, click the arrow of the same menu. 30. The main area of the studio is made of a rectangular box called a form and is typically identified as Form1; if you create additional forms, by default, they would be identified as Form2, Form3, or FormX. 31. The Toolbox provides the necessary tools to create your applications.

The Toolbox comes with a lot of controls to start working. It can also be enhanced with more objects that we will review as we move on. Like the items on the Standard toolbar, the controls on the Toolbox are not always obvious. To find out what kind of control is displayed, position your mouse on a control and observe the tool tip. Review different items until you find the one you want. To use a control from the Toolbox, click it and draw it on your form. When no object is being used, the Pointer is selected. Once you select one of the controls, the pointer loses focus and you can use the selected control. We will learn how to use the controls in another lesson. Notice that the right section of the Standard toolbar displays the dimensions of the form.

32. The Properties Window displays a list of the properties associated with each control or
form that are part of your project. A property is anything that characterizes an object. When you look at a control, you see that it has a size, a color, a caption (something written on some controls; for example, on top of the form, the caption is Form1), etc. Different controls have different sets of properties. To experiment with controls properties, on the Properties Window, click the (Name) field and type frmTimeSheet Notice that even though you clicked (Name), the name has been changed.

33. Click the Caption field and type: Time Sheet


34. The Project Explorer window gives a list of the forms and modules that are part of the current project. To experiment with the Project Explorer window, click the Toggle Folders button . Notice that the folders are collapsed. To expand the folders, click the Toggle Folders button again. 35. 36. Still on the Project Explorer window, click View Code. You are presented with the Code Editor window.

37. To send the Code Editor window to the background again, on the Project Explorer window,
click the View Object button .

38. The Form Layout window allows you to position your form or forms with regard to the rest of the screen. It uses a graphical interface to guide you. To experiment with it, click the small image inside the small screen and drag to the upper left corner inside the small screen. Notice that the small image can move. 39. 40. Drag the small rectangle in the Form Layout screen again and position it to the middlw of the small screen. 41. To verify the result, press F5 to run the form. Notice that the running form displays in the center of the screen. 42. To close the running form, click its close button.

Saving a Project
A program you create in Microsoft Visual Studio (of course, this includes VB) is called a project. A Microsoft Visual Basic project is made of various objects that you create or add as your program grows. Therefore, when saving a program, you have to save the main project and its objects. There are two categorical pieces of information you should provide when saving a program: the project's location and a name for each object or file. The location is a folder where you store the program for easy retrieval when needed. A name for each component allows you to identify it as compared to other objects of the same program. An object's name can contain a combination of up to 255 characters. Refrain from using fancy characters. Assign a name made of characters a to z, A to Z, and digits 0 to 9.

Saving the Project


1. To start a new project, on the main menu, click File -> New Project 2. In the New Project dialog box, double-click Standard EXE. If you are asked whether you want to save the project, click No 3. To save the current project, on the main menu, click File -> Save Project 4. Click the arrow of the Save In combo box and select the C: drive

5. On the Save File As dialog box, click the Create New Folder button 6. Type MS Visual Basic and press Enter twice to display the new folder in the Save In
combo box

7. Click the Create New Folder button

again

8. Type Exercise1 and press Enter twice to display the new folder in the Save In combo box

9. In the File Name edit box, change the name of the file to frmMain and press Enter to

save the file

10. Change the name of the project to Exercise1

11. Click Save. Depending on your package (or no package) of MS Visual Studio, you may be asked whether you want to add this project to Source Safe; if you are prompted so, click No 12. Close Microsoft Visual Basic

Copyright 2001-2004 FunctionX, Inc.

Next

Introduction to Windows Controls

Overview of Controls
Introduction
A Windows control, also called a control, is an object that allows the user to interact with the computer. Such an object must be displayed on the screen or somehow made available to the user who can then click it, move it, resize it, type in it or retrieve something from it. Because there are so many operations a user can perform on the computer, controls are separate in categories according to their functionality and their roles in an application. Nevertheless, to make your application effective, as the developer, you will decide what the user can do with your application and what should be excluded. When creating your application, you add controls to it as you judge them relevant for the possible assignments that can be performed on your application. While working, you will deal with two big categories of controls: those that can act parents and those that (always) need some parenting.

Controls Fundamentals
You as the developer will decide what control should be available in your application, what functionality that control should provide, and what the user can do with it. Some of the functionality is controlled by the operating system because such a functionality is part of the computer's behavior. Some other aspects are under your control. When creating your application, you will most likely start from a form. We will have a better study of forms when the time comes. Other controls are added to the form. To use one of them, you will get it from an object called the Toolbox and then add them to the form. Once a control is available to you, you can customize its appearance and behavior, which is the subject of this site. To implement their intended assignment, one of the most regular operations a control perform is to fire events.

Control Design
Introduction
To interactive with the computer, the user submits requests to the machine and the computer processes these assignments. This exchange of information is done through objects called controls, also called components. Almost any object you see on your screen is a window and we are going to learn how to create and use them with Visual Basic. When you start Visual Basic and select Standard EXE, it creates a form for you: this is the first and the most commonly object you will use in your applications.

Practical Learning: Starting Controls


Start Microsoft Visual Basic 6 and accept to create a Standard EXE application by pressing Enter

Control Selection

To provide the necessary functionality for your application, you will use controls from the Toolbox and add them to another component such as a form. The control you pick up from the Toolbox is also referred to as a child control. the control or object on which you add a child control is referred to as its parent or host. This can be a form or another object that has the capacity to host other controls. To identify a control on the Toolbox, you can position the mouse on it. A tool tip would appear:

From now on, we will call each control by the tool tip that appears on it. To add a control to a host, on the toolbox, you can double-click it. Alternatively, you can click the control on the toolbox and then "draw" it on the host. You can keep adding controls to a host as necessary. If you want to add a control over and over again, you can press and hold Ctrl, click the control on the Toolbox, then draw it in the desired area on the host. Every time you draw, the control would be added to the form or host. Once you have added enough controls, you can release Ctrl. If you select a control by mistake, you can simply click another. The new one would become selected. If you clicked a control but don't want any control at all, you can click the Pointer button .

You cannot select more than one control to add to a host.

Practical Learning: Designing Controls


1. To add a control to the form, on the Toolbox, double-click the TextBox control

2. To add another control, on the Toolbox, click the CommandButton


3. On the form, click and hold your mouse on the top left corner in the body of the form. Then drag right and down to draw a rectangle (don't try to be precise):

4. Release the mouse

Selecting Controls
Most of the time, before doing anything on a control, you must first select it. In the same way, to perform an action on a group of controls, you must first select them. To select one control on the form, you can just click it. Alternatively, you can click and hold the mouse somewhere on the form but close to the control. Then drag as if you were drawing a line. Once you have touched the control, you can release the mouse. The control would be selected. To select more than one control at random, click one of them, press and hold Shift or Ctrl, then click each of the desired controls. Once you are satisfied with the group, release the key you were pressing. To select more than one control in a range, click and drag to draw a rectangle. Any control that would be touched by the fake rectangle would be included in the group.

Practical Learning: Selecting Controls


1. On the form, click the TextBox object. Notice that it has been selected 2. Click an empty area on the form to select the form 3. To select controls using the mouse and keyboard, click the CommandButton 4. Press and hold Shift, then click the TextBox and release Shift. Notice that both controls have been selected

Deleting Controls
If you have one of more controls that you don't need anymore, you can remove them from your form. To remove one control, select it and press Delete. To remove many controls, first select them, then press Delete. You can also select a control or a group of control, then rightclick and click Cut.

Practical Learning: Deleting Controls


1. Click the TextBox on the form to select it 2. Press Delete to remove it 3. Right-click the CommandButton on the form and click Cut

Properties of Controls
Introduction
If you access a code when designing the application, it is said that you are working at design time. If you access a control with code, it is said that you are at run time. Therefore, design time refers to the form being designed while displaying in Visual Basic. Run time refers to the time the control is displaying to the user. After adding a control to the application, you can customize it. For example, you can change some parts of its appearance. You can also give it assignments. These are done from two parts: the Properties window and the Code editor. Controls are broadly classified in two groups. A control is referred to as graphical if the user can see it. There are other controls that will work behind the scenes at run time. Such control are not graphical (an example is the Timer). They can be referred to as static. The user never sees these controls. There are some other controls not considered graphical because the user cannot directly change their values. For example, a control that displays only text (such is the case for the Label) is not considered graphical. A Windows control is an object that imitates a real world object. As such, it is made of characteristics that define it. A characteristic is also called a property. A property is any aspect that describes an object. Once you have a control, you can change its properties in the Properties window. This is considered that you are controlling the properties at "design time". To change the properties of a control, first select it, then proceed with changing the desired properties in the Properties window. To control a form's properties with code, you will refer to itself. A form refers to itself using the Me keyword. To change the properties of a control with code, you refer to it by its name. Whether dealing with a form or a control, after typing Me for the form, or the name of the control, type a period. A list of the properties (and possibly other objects that we will know eventually) will appear. You can continue typing or simply select from the list. And continue with your coding. Not all properties can be changed with code.

Controls Names
Everything on a computer must have a name. In the same way, to refer to a control in your code, you must give it a name. When you add a new control to your application, it receives a default name. When necessary, which will be almost all the time, you should change that name to a more recognizable one. To change the name of a control, first select it. Then, in the Properties window, click (Name) and type the desired name. Refrain from changing the name of a control with code.

Practical Learning: Naming Controls


1. On the Toolbox, double-click the Timer
2. While the control is still selected on the form, in the Properties window, click (Name)

3. Type tmrClock and press Enter

The Control's Location


We saw that when you double-click a control from the Toolbox, it gets positioned on the form or host. We also mentioned that you can draw it, which also gives it a position. The position of a control is important for the operating system to always know where the control is. The position of a control is also referred to as its location. The location of a control uses a coordinate system whose origin is located on the top-left corner of its parent. For a form, this origin is located in its top-left section just under the title bar:

Any control positioned on the form bases its location on this origin. After adding or drawing a control, its positioned is set so its left border has a distance called Left from the origin of its parent. In the same way, the distance from its top border to the top border of its parent is

called Top. This can be represented as follows:

There are various ways you can change the location of a control. After adding it to its host, to change its coordinates, click and drag it to the desired location. You can also move a control using the keyboard. To do this, click the control to select it. Then press and hold Ctrl. While the Ctrl key is down, press: The down arrow key to move down The up arrow key to move up The right arrow key to move to the right The left arrow key to move left

Once you get to the desired location, release the Ctrl key. To be more precise, you can also change the values of the Left and/or the Top properties in the Properties window. To programmatically change the location of a control, in the Code Editor, in response to an action, type the control's name followed by the period operator, the desired property Left or Top, the assignment operator, and the new value.

Practical Learning: Locating Controls


1. On the form, click the timer and hold the mouse down, then drag it to the top-left section
of the form

2. Notice that a tool tip displays the current coordinates of the control

3. From the Toolbox, double-click the TextBox


4. To move it, press and hold Ctrl. Then press the up arrow key 4 times and the right arrow key 3 times

5. From the Toolbox, double-click the CommandButton


6. While the new button is still selected, in the Properties, click (Name). Type Please and press Enter 7. To programmatically move it, double-click an unoccupied area on the form and type the following: Private Sub Form_Load() Please.Left = 340 Please.Top = 1200 End Sub

8. Press F5 to test the application

9. Close it and return to MSVB

The Control's Dimensions


Because its location, a control is also visibly identified by its dimensions. The width is the distance from its left border to its right border. This dimension is represented by the Width property. The height is the distance from its top to its bottom border. This dimension is represented by the Height property:

As done with the location, there are various ways you can specify or control the dimensions of an object. If you click a control on the Toolbox, you can click and hold the mouse on the form then drag. While dragging, a rectangle would guide you with a tool tip that display the dimensions, live. Once you get the desired dimensions, you can release the mouse. If the control is already located on the form, to change its dimensions, after clicking it, position the mouse on one of its 8 handles. You would get one of the following cursors depending on where the mouse is located: Pointer Role Shrinks or heightens the control Resizes the control in North-East <-> South-West direction Narrows or widens the control Resizes the control in North-West <-> South-East direction You can also resize a control using the keyboard. To do this, click the control to select it. Then

press and hold Shift. While holding Shift, press: The down arrow key to heighten the control while its top border is locked The up arrow key to shrink the control while its top border is locked The right arrow key to widen the control to the right The left arrow key to narrow the control while its left border is locked

Once you reach the desired dimension, release Shift. You can also change the dimensions of a control to known values. To do this, after selecting the control on the form, in the Properties window, change the values of the Width and/or the Height fields. To change the dimensions programmatically, assign the desired values to its Width and/or Height properties. Not all controls can be resized. The controls that don't appear to the user, such as the Timer cannot be resized.

Practical Learning: Resizing Controls


1. On the form, click the Command1 control and notice the 8 handles that surround it

2. Position the mouse in the middle bottom handle until the mouse cursor appears vertical

3. Click and hold the mouse down. Then drag down by 2 units and release the mouse 4. On the form, click the Text1 control to give it focus 5. Press and hold Shift. Then press the right arrow key 3 times and the down arrow key 2 times to resize the control 6. Release Shift

Controls Text and Caption


Some controls are meant to display or sometimes request text from the user. For such controls, this text is referred to as caption while it is simply called text for some other controls. This property is not available for all controls.

If a control displays text, it then has a Caption or a Text field in the Properties window. After adding such a control to a form, its Caption or its Text field may the same text as its name. At design time, to change the text of the control, click either its Caption or its Text field and type the desired value. For most controls, there are no strict rules to follow for this text. Therefore, it is your responsibility to type the right value. The text provided in a Caption or Text fields of a text-based control can only be set as is at during design. If you want the text to change while the application is running, you can format it. For example, such a control can display the current time or the name of the user who is logged in. These format attributes cannot be set at deign time. To change the text of a textbased control at run time, either assign a simple string or provide a formatted string to either the Caption or the Text property.

Practical Learning: Using Text in a Control


1. Press F5 to test the application 2. Select the Text1 text in the text control and type Come On! 3. Close the form and return to MSVB

Control's Visibility
For the user to directly use a control, he or she must be able to see that control. For example, the user cannot type an employee's name if there is not control to receive that text. Based on this, objects provide the ability to control their visibility or absence. This characteristic is controlled by the Visible property. The default visibility of graphical controls have their Visible property set to True. To hide a control, set its Visible property to False. You can change this value at design time using the Properties window. You can also change it programmatically.

Practical Learning: Controlling an Object's Visibility


1. On the form, click the Command1 button 2. In the Properties window, double-click Visible to change it from True to False 3. Press F5 to test the application 4. Notice that the button is invisible 5. Select the Text1 text in the text control and type Zimbabwe 6. Close the form and return to MSVB

Control's Availability
Even if a control is visibility, it doesn't necessary make its services available to the user. This means that a control can enable its role or lock them. When a control is enabled, the user can click it or type in it. You can also prevent this type of action by disabling the control. The ability to enable or disable an object is controlled by the Enabled property. If you set it to True, which is its default value, the service of the control are available to the user. If you set

this property to False, the control appears gray.

Practical Learning: Disabling a Control


1. On the form, click the Text1 control 2. In the Properties window, double-click Enabled to change its value to False 3. Press F5 to test the application 4. Try typing something in the text box. Notice that the control is disabled 5. Click the form and return to MSVB 6. Select both the text box and the button on the form. In the Properties window, set both their Enabled and their Visible properties to True 7. Click somewhere on the form to make sure nothing is selected

Tab Sequence
When a form contains many controls, the user can navigate to different ones by clicking them. Alternatively, the user can press Tab to move the focus from one control to another. The controls that can be accessed using the Tab key belong to a group. For a control to participate to this group, it must have its TabStop property set to True. All graphical controls are automatically added to this group by default when they are picked from the Toolbox and added to a form. If you don't want a control to receive focus as a result of the user pressing Tab, set its TabStop to False. Each control in the Tab sequence group has a unique incremental number. This number is called TabIndex. The first control added receives a number of 0. The second receives 1, etc. The control whose TabIndex is the lowest would receive focus when the form comes up. If you want, you can change the default sequence by changing the TabIndex values of the controls.

Previous

Copyright 2002-2005 FunctionX, Inc.

Next

Controls Messages and Events


Controls Events
Introduction

Because your computer is made of various objects, these are under the control of three entities: The operating system is first in charge of all the basic operations that must be performed in order for the computer to be usable. Some of these include checking that the various parts (hardware) are ready to be used, displaying the time, checking that a printer is working, etc The person who creates a program, that is you, is in charge of a particular application. For example, as we will learn on this site, when you create a program, you decide what it can do and what it shouldn't do. You also decide if and when it should do something The user, that is, a person who uses the computer or a program that you have written also controls such aspects as when to open a program, when to perform a certain processing

Every time you do something on the computer, the object you interact with composes a message like an email and sends that message to another entity, normally the operating system, that can process that message. This means that, whether you click an object, type something using the keyboard, move the mouse on the screen, or press and click at the same time, a message is composed. Once a message has been composed, it is sent to the OS. Once a message is received, it is analyzed and interpreted. Then a result may be sent to the application from where the message was sent. The action of sending a message is called an event. There are so many objects you can use on a computer, and/or on an application, that Microsoft Windows is referred to as an event-driven operating system. After the computer has been launched, it becomes "static" and displays a blank desktop to the user. For example, the computer cannot start a program on its own and it cannot just start typing words on the desktop... (Even if this happens as a result of a script, it doesn't mean that the computer did it on its own, it means that somebody asked it to do it; it is important to understand that the computer is a dumb object that doesn't think. For the computer to do something automatically, something has to ask to do it, whether it is a script you wrote (Windows Script Host(WSH)) or a virus somebody sent you; the computer can't just decide to do something on its own.). Because there are so many actions that can be performed, the computer cannot predict what should be done next. Therefore, it leaves it up to the user to initiate an action. Again, because there are so many things that could happen at any time, for the computer to do what is needed, it expects good and precise directives. Based on this, Microsoft Windows uses a mechanism like a mail you send to somebody through the post office. When a message is sent, some conditions must be met for the message to be processed. If a message is not well defined, either the computer would ignore it (best case scenario) or it would crash. For this reason, as a programmer, you need to know what messages you can send (there are are so many messages for different reasons), when you can send a certain message (you cannot just send any message at any time), why (it is important that you know the reason for sending a message, otherwise you may send the right message at the right time but the message cannot be processed because either it is not needed, not necessary, or not efficient). After a message has been formulated, it must be sent. The action of sending a message is called an event.

In order for a message to be processed, it must provide at least three pieces of information.

1. The Sender of a Message


The first piece of information necessary for each message is: WHO sent the message? The computer contains many applications and each application is made of various internal objects. Any application can create a message anytime and send it. Since there can be so many messages sent to the operating system at any time, the application or the object that sent the message must be identified. In some cases the operating system may need to send a response when it has finished processing the message, in some other cases, it needs to identify the object so it would know how the message must be processed. Once the sender of a message has been identified, its event is considered as a private matter because only that object is concerned with the message. If this action is not private, it will be qualified as Public. Therefore, the coding of each event starts with the Private keyword: Private An event is really an assignment you ask the application, the form, or the control to perform in response to a particular action happening. You can even ask an object to perform an action based on the behavior of another object or based on the computer doing something (such as singing when the clock displays 12:00 PM). Since there are so many assignments you will give to different components to perform, these actions are called procedures. There are two kinds of procedures: Functions and Sub procedures. Both are written in Visual Basic. A Function is a general assignment you write in Visual Basic. This assignment is a resource for other events or actions to get results. For example, if many controls on a form would require a particular value or the result of a particular calculation, you can write a function that all desired events can refer to and get the appropriate result. Since other events and functions would expect a particular result from it, a function is expected to Return a value. We will learn what kind of value a function can return. A Sub procedure is a form of assignment that applies to an event associated with particular application, form, or control. It is used to "enclose" the coded assignment you want an event to carry. Since each event is a procedure, now we have: Private Sub As mentioned already, the object that sent a message must be identified. Therefore, the Sub keyword would be followed by that object: Private Sub MessageSender

2. The Type of Message

After the sender of a message has been identified, the operating system would need to know: WHAT message was sent? There are various objects in the computer and applications. Some objects can send the same type of message. Some other objects have particular messages that only they can send. Because one type of object can send different types of messages, even if the operating system has been able to identify the sender, it needs to know the type of message that was sent. By convention, and as we will see later on, the name of a message produces the name of the event

By convention, the name of the event is written after the name of the object that sent the message. To distinguish between a control's name and its event, Visual Basic uses a convention of displaying an underscore between them, like this: Private Sub MessageSender_Event

3. The Message Accessories


Once the operating system knows what object sent the message and what that message is, depending on the message, it may need to know: the accessories needed to process the message

While one message may appear easy, such as clicking an object, another message would need additional information such as where (the coordinates of the mouse cursor) the clicking occurred. Therefore, some events will need some values from you. In some situations it will be one value; in this case the accessory is called an argument. Another type of event may need more than one accessory, thus many arguments. Again, depending on the event, this could be one argument, or it could be as many arguments as necessary. When we move on, we will see what events need what argument(s) The argument or group of arguments that the event may need is listed in parentheses on the right side of the event name, like this: Private Sub MessageSender_Event(Argument1, Argument2, Argument_n) Even if an event doesn't need an argument, you must provide empty parentheses, like this: Private Sub MessageSender_Event()

The Body of an Event


The subject of the assignment is called the body. It starts with the Private Sub line and ends with a line identified as End Sub. Between these two lines, you specify what the event is supposed to accomplish. Some events just need to know what you want them to do, for example, you can ask a button to close a form when that button is clicked. On the other hand, when the user clicks somewhere on an object, you could ask the object to display something depending on the button the user clicked. In this case, the event code would like to know what button was clicked. The above introduction was meant to show you what a coded event looks like. Microsoft Visual Basic will do a lot of work for you behind the scenes. For example, it will always set a beginning and end event for you. It will also specify the names (and types) of arguments for you. This means that Visual Basic always writes a skeleton code for your event; you can then customize

it as you see fit.

Practical Learning: Starting an Event


1. Start Microsoft Visual Basic 6.0 2. On the opening dialog box, make sure Standard EXE is selected and click Open 3. On the main menu, click View -> Code

4. In the empty window, type Private Sub Form_Click

5. Press Enter

6. Notice that Visual Basic added the parentheses and the End Sub line 7. In the Code window, notice that the Object combo box is displaying Form
8. Click the arrow of the Object combo box to display its list:

9. Click the arrow of the Procedure combo box and, in the list, click MouseDown

10. Notice the section of the MouseDown event. Also notice that this event has a few arguments 11. We will eventually learn what the writings of these arguments mean. In the Object combo box, notice that Text1 is still displaying. 12. In the Code window, click on one of the form events. 13. Notice that the Object combo box has automatically changed.

Categories of Events
The Keyboard Events
Word processing consists of manipulating text and characters on your computer until you get the fantastic result you long for. To display these characters, you press some keys on your keyboard. If the application is configured to receive text, your pressing actions will display characters on the screen. The keyboard is also used to perform various other actions such as accepting what a dialog box displays or dismissing one. When you press the keys on your keyboard, you are sending keyboard events.

The Click Event


The mouse has become a very important object of computer use. It is used by pressing one of its buttons.

The Double-Click Event


When you press the left mouse button once, the event is called the Click event. Another action you can perform is to click the button twice but very fast. This is referred to as double-clicking.

The Right-Click Event


Since Microsoft Windows 95, the mouse buttons are intensely used and both buttons have become important object of the computer daily use. By default, the users click the left mouse button for all routine work. The other button, the right one, is used in various circumstances, such as displaying a context menu. The Right-Click action is performed by clicking the right mouse button. The actions that the right-clicking produce completely depend on the programmer. When writing code for the right-click button, you will have to find out what button was clicked, and then write code accordingly.

The Focus Events


Microsoft Windows operating systems allow you to work on more that one application at the same time. They also allow you to work on many forms as the computer can handle. But only one application can receive instructions at a given time. For example, although you can edit text on a word processor while a spreadsheet is running in the background, you can only perform one action at a time. You have the ability to display the desired application when needed. This applies to applications. Many dialog boxes have more than one input control, such as the Font dialog box we used earlier. Although all these controls are available, you can work from only one control at a time. If many applications are running on your computer while you are working, the program that is currently being edited or receiving input from you is said to have focus. If you have two forms, you can open both of them but at a given time, you can work on only one of them. On a form that is equipped with many controls, only one control can be changed at a time; such a control is said to have focus. The application or the form that has focus usually has its title bar with the active window color as set in Control Panel. In a form with many controls, the one that has focus will usually have a cursor or a dotted line around its selection. When an application, a form, or a control has focus, Microsoft Visual Basic applies the GotFocus event. If the focus shifts to another application, form, or control, Microsoft applies the LostFocus to the same component.

Launching and Loading A Program


Your computer is filled with a lot of programs, some of which you use all the time, some of which you use some time to time, and some of which you probably never or rarely use. Since the computer can't predict what you want to do, it keeps all these programs in a storage area called the hard drive. They simply stay there and wait. When you want to use one of these programs, you ask the computer to bring it to you. There is another, temporary, storage area in your computer called the memory (RAM). This is where the computer puts the programs you are using currently. When, you decide to use a program, the computer brings it up. When you have finished using the program, the computer puts it back into the hard drive. Of course, the computer can put as many programs as possible into the memory (or as many as the capacities of the computer allow it). To use a program, you have to "Load" it into memory (the computer will do it for you). And to

load a program you have to select and start it. That's why you need to find it and... When a program starts, it is said to be launched. Visual Basic considers that the program is Opening. It takes just a few seconds for a program to launch or open. Some of them display a "Splash Screen" while they are launching. After the program has been launched, it is said to be Loaded. Once a program is loaded, it is said to be running. Actually, loaded and running would mean the same thing, especially in Visual Basic.

Practical Learning: Loading a Program


1. To start WordPad, click Start -> (All) Programs -> Accessories -> WordPad. 2. While the program is Opening, you should see a brief splash screen (since WordPad is a small application (not by programming standard, but as far as the users are concerned), the splash screen might not appear, or it would be very brief):

3. Notice that after launching, WordPad is opened. Visual Basic says that WordPad is Loaded:

Previous

Copyright 2002-2005 FunctionX, Inc.

Next

Variables and Data Types


Introduction to Variables
Overview
When you write a program as a time sheet, you may decide that a user will type her weekly hours in one box and her salary in another box; then another box will display her weekly salary. When you are designing the program, you cannot predict the names of the people who will be using the program and you definitely cannot know the weekly hours they will get week after week. What you have to do is ask the computer to create temporary storage areas that

one user can use while the program is running. If that box can be used to store a salary, when another user is using the same program, that box should be ready to receive new inputs, new salary for that other user. The computer memory is made of small storage areas used to hold the things that a program needs while it is running. As a programmer, you specify these things, or you provide them to the computer; the computer then puts them in these storage areas. When you need one of them, you let the computer know. The machine located it and makes it available to you to use as you see fit. A variable is a value you are ask the computer to store in its memory while the program is running.

Using a Variable
As stated already, a variable is an area of computer memory you use in your program. To use a variable, you must give it a name. There are rules you should, and usually must, follow when naming your variables. The name of a variable: Must begin with a letter Cannot have a period (remember that we use the period to set a property; in other words the period is an operator) Can have up to 255 characters. Please, just because it is allowed, don't use 255 characters. Must be unique inside of the procedure or the module it is used in (we will learn what a module is)

Once a variable has a name, you can use it as you see fit. For example, you can assign it a value and then use the variable in your program as if it represented that value.

Practical Learning: Using a Variable


1. Start Microsoft Visual Basic and create a new application using Standard EXE 2. Right-click the form and click View Code 3. In the Code Editor, click the arrow of the Object combo box and select Form

4. To use a variable, implement the Load event as follows:


Private Sub Form_Load() SomeColor = vbRed BackColor = SomeColor End Sub 5. Press F5 to test the application. Notice that it appears red 6. After using the form, close it and return to MSVB

Variable Declaration
Unlike languages referred to as strongly typed, Visual Basic is so flexible you can use any

variable just by specifying its name. When you provide this name, the computer directly creates an area in memory for it. Based on this, consider the following code section: Private Sub Form_Click() SameColor = vbBlue SomeColor = vbRed SumColor = vbRed BackColor = SameColor End Sub Private Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) SameColor = vbBlue SomeColor = vbRed SumColor = vbGreen BackColor = SumColor End Sub Private Sub Form_Load() SameColor = vbBlue SomeColor = vbRed SumColor = vbGreen BackColor = SomeColor End Sub If you execute this program, when the form displays, it would be painted in red. If the user clicks the form, it would be painted in blue. If the user presses a key, the form would be painted in green. There is some confusion in the program. It uses a variable that seems to have a name but initialize three times with different colors. Visual Basic allows you to directly use any name for a variable as you see fit. Fortunately, to eliminate the possibility of this confusion, you can first let Visual Basic know that you will be using a certain variable. Informing Visual Basic about a variable prior to using that variable is referred to as declaring a variable. When a variable has been declared, just like the variable not declared, the computer reserves an area of memory for it. To declare a variable, type the Dim keyword, like this: Dim On the right side of Dim, you must type a name for the variable, following the same rules we reviewed above. Here is an example of declaring and using a variable: Private Sub Form_Load() Dim BackgroundColor BackgroundColor = vbRed

BackColor = BackgroundColor End Sub Declaring a variable simply communicates to Visual Basic the name of that variable. You can still use a mix of declared and not-declared variable. This is demonstrated in the following event:

Once again, the compiler believes that you are using two variables; one is called BackgroundColor and the other is called SomeColor. This can still create a great deal of confusion because you may be trying to use the same variable referred to twice. The solution to this possible confusion is to tell Visual Basic that a variable cannot be used if it has not been primarily declared. To communicate this, on top of each file you use in the Code Editor, type Option Explicit This can also be done automatically for each file by checking the Require Variable Declaration in the Options dialog box.

Practical Learning: Using a Variable


1. On the main menu of Microsoft Visual Basic, click Tools -> Options...

2. Click the Editor property page. In the Code Settings section, put a check mark in the
Require Variable Declaration check box

3. Click OK 4. Close Visual Basic without saving the project 5. Start Microsoft Visual Basic and create a new application using Standard EXE 6. Right-click the form and click View Code 7. In the Code Editor, click the arrow of the Object combo box and select Form

8. To use a variable, implement the Load event as follows:

9. Press F5 to test the application

10. Notice that you receive an error:

11. Click OK

12. On the Standard toolbar, click the End button


13. Change the Load event as follows: Private Sub Form_Load() Dim BackgroundColor BackgroundColor = vbRed BackColor = BackgroundColor End Sub 14. After using the form, close it and return to MSVB 15. Click the arrow of the Procedure combo box and select Click o Implement the events as follows

Introduction to Data Types


Introduction
When you decide to use a variable, you are in fact asking the computer to use a certain amount of space to hold that variable. Since different variables will be used for different purposes, you should specify the kind of variable you intend to use, then the computer will figure out how much space is needed for a particular variable. Each variable you use will utilize a certain amount of space in the computer's memory. Before declaring or using a variable, first decide what kind of role that variable will play in your program. Different variables are meant for different situations. The kind of variable you want to use is referred to as a data type. To specify the kind of variable you want to use, you type the

As keyword on the right side of the variable's name. The formula to declare such a variable is: Dim VariableName As DataType Once you know what kind of variable you will need, choose the appropriate data type. Data types are organized in categories such as numbers, characters, or other objects.

String
A string is an empty text, a letter, a word or a group of words considered. To declare a string variable, use the String data type. Here is an example: Private Sub Form_Load() Dim CountryName As String End Sub After declaring the variable, you can initialize. If you want its area of memory to be empty, you can assign it two double-quotes. Here is an example: Private Sub Form_Load() Dim CountryName As String CountryName = "" End Sub If you want to store something in the memory space allocated to the variable, assign it a word or group of words included between double-quotes. Here is an example: Private Sub Form_Load() Dim CountryName As String CountryName = "Great Britain" End Sub You can also initialize a string variable with another.

Boolean
A Boolean variable is one whose value can be only either True or False. To declare such a variable, use the Boolean keyword. Here is an example: Private Sub Form_Load() Dim IsMarried As Boolean End Sub After declaring a Boolean variable, you can initialize by assigning it either True or False. Here is an example: Private Sub Form_Load() Dim IsMarried As Boolean IsMarried = False End Sub Like any other variable, after initializing the variable, it keeps its value until you change its

value again.

Numeric Data Types


Introduction
A natural number is one that contains only one digit or a combination of digits and no other character, except those added to make it easier to read. Examples of natural numbers are 122, 8, and 2864347. When a natural number is too long, such 3253754343, to make it easier to read, the thousands are separated by a special character. This character depends on the language or group of language and it is called the thousands separator. For US English, this character is the comma. The thousands separator symbol is mainly used only to make the number easier to read. To support different scenarios, Microsoft provides different types of natural numbers

Byte
A byte is a small natural positive number that r

Visual Basic Operators


Operators and Operands
Introduction
An operation is an action performed on one or more values either to modify one value or to produce a new value by combining existing value. Therefore, an operation is performed using at least one symbol and one value. The symbol used in an operation is called an operator. A variable or a value involved in an operation is called an operand. A unary operator is an operator that performs its operation on only one operand. An operator is referred to as binary if it operates on two operands.

The Assignment Operator =


The assignment operation is used to make a copy of a value, a variable, or the content of a control and give the copy to another variable. The assignment operation is performed with the

= sign. After you have declared a variable, before using it, it must have a value. One way you can give a value to a variable is to assign one. For example, if you had declared a variable named NumberOfTracks. You an store a number like 16 in that variable by assigning it the value. You would type NumberOfTracks = 16 as in the following: Private Sub Form_Load() Dim NumberOfTracks As Integer NumberOfTracks = 16 End Sub When the assignment operator is provided to a variable as a starting value for the variable, this is referred to as initializing the variable. You can also assign a variable to another as in Variable1 = Variable2. Using this approach, the item on the left side of the assignment operator must be variable and never a (constant) number.

Unary Operators: The Positive Operator +


Algebra uses a type of ruler to classify numbers. This ruler has a middle position of zero. The numbers on the left side of the 0 are referred to as negative while the numbers on the right side of the rulers are considered positive: - - -6 -6 -5 -5 -4 -4 -3 -3 -2 -2 -1 0 -1 1 2 3 4 5 6 + 1 2 3 4 5 6 +

A value on the right side of 0 is considered positive. To express that a number is positive, you can write a + sign on its left. Examples are +4, +228, +90335. In this case the + symbol is called a unary operator because it acts on only one operand. The positive unary operator, when used, must be positioned on the left side of its operand, never on the right side. As a mathematical convention, when a value is positive, you don't need to express it with the + operator. Just writing the number without any symbol signifies that the number is positive. Therefore, the numbers +4, +228, and +90335 can be, and are better, expressed as 4, 228, 90335. Because the value does not display a sign, it is referred as unsigned.

Practical Learning: Using Operators


1. Start Microsoft Visual Basic and, on the opening dialog box, double-click Standard EXE 2. To save the project, on the main menu, click File -> Save Project 3. Locate your MS Visual Basic folder created in the first lesson and display it in the Save In combo box

4. Click the Create New Folder button. Type Operations and press Enter twice to display it
in the Save In combo box

5. Click Save twice to save the form and the project 6. Using the controls on the Toolbox, design the form as follows:

Control Label TextBox

Caption Number

Name txtOperand

CommandButton Operation cmdOperation 7. Double-click the Operation button and implement its event as follows: Private Sub cmdOperation_Click() txtOperand = +248.64 End Sub 8. Press F5 to test the application 9. After using it, close the form

Unary Operators: The Negative Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.

Practical Learning: Using The Negative Operator


1. Change the code of the form as follows: Private Sub cmdOperation_Click() txtOperand = -972.405 End Sub 2. Press F5 to test the application 3. After using it, close the form

Arithmetic Operators

The Addition +
The addition is performed with the + sign. It is used to add one value to another. To add two numbers, such as 225 and 64, you could use 225 + 64. The result would be 289. The addition is also used to add the values of two variables. For example, you could use CDbl(txtMondayHours) + CDbl(txtTuesdayHours) to get a total number of hours worked on Monday and Tuesday. The result could be stored in another control.

Practical Learning: Using the Addition Operator


1. Change the design of the form as follows:

Control Label TextBox Label TextBox

Caption First Name:

Name txtOperand1

Last Name: txtOperand2 cmdAddition txtResult Result:

CommandButton Addition Label TextBox

2. Double-click the Addition button and change its code as follows: Private Dim Dim Dim Sub cmdAddition_Click() dblOperand1 As String dblOperand2 As String dblResult As String

dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 + " " + dblOperand2 txtResult = dblResult End Sub

3. Test the application. Enter a name one the First Name text box and another name in the
Last Name text box then click Addition

4. After using the form, close it

The Subtraction The subtraction operation is performed using the - sign. This operation produces the difference of two or more numbers. It could also be used to display a number as a negative value. To subtract 28 from 65, you express this with 65-28. The subtraction can also be used to subtract the values of two values.

Practical Learning: Using the Subtraction Operator


1. Change the design of the form as follows:

Control Label TextBox Label TextBox

Caption Number 1:

Name txtOperand1

Number 2: txtOperand2 cmdAddition

CommandButton Addition Label TextBox Result:

CommandButton Subtraction cmdSubtraction txtResult

2. Double-click the Addition button and change its code as follows:

Private Dim Dim Dim

Sub cmdSubtration_Click() dblOperand1 As Double dblOperand2 As Double dblResult As Double

dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 - dblOperand2 txtResult = dblResult End Sub

3. Test the application. Enter a number one the Number text box and another number in the
Number text box then click Subtraction

4. After using the form, close it

The Multiplication *
The multiplication operation allows you to add a number to itself a certain number of times set by another number. The multiplication operation is performed using the * sign. For example, to add 25 to itself 3 times, you would perform the operation as 25 * 3

Practical Learning: Using the Multiplication Operator


1. Add a new CommandButton to the right of the Subtraction button

2. Change its Name to cmdMultiplication and its Caption to Multiplication

3. Double-click the Multiplication button and change its code as follows: Private Dim Dim Dim Sub cmdSubtration_Click() dblOperand1 As Double dblOperand2 As Double dblResult As Double

dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 * dblOperand2 txtResult = dblResult End Sub

4. Test the application. Enter a number one the Number text box and another number in the
Number text box then click Multiplication

5. After using the form, close it

The Integer Division: \


Dividing an item means cutting it in pieces or fractions of a set value. Therefore, the division is used to get the fraction of one number in terms of another. Microsoft Visual Basic provides two types of operations for the division. If you want the result of the operation to be a natural number, called an integer, use the backlash operator "\" as the divisor. The formula to use is: Value1 \ Value2 This operation can be performed on two types of valid numbers, with or without decimal parts. After the operation, the result would be a natural number.

Practical Learning: Using the Integer Division


1. Add a new CommandButton to the right of the Subtraction button

2. Change its Name to cmdDivision and its Caption to Division

3. Double-click the Division button and change its code as follows: Private Dim Dim Dim Sub cmdSubtration_Click() dblOperand1 As Double dblOperand2 As Double dblResult As Double

dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 \ dblOperand2 txtResult = dblResult End Sub

4. Test the application. Enter a number one the Number text box and another number in the
Number text box then click Division

5. After using the form, close it

The Decimal Division: /


The second type of division results in a decimal number. It is performed with the forward slash "/". Its formula is: Value1 / Value2 After the operation is performed, the result is a decimal number.

Logical Comparisons
Logical Operations
Introduction
Sometimes while a person is using your program, you may need to check whether something is true or it is false. This type of operation is performed using operators referred to as comparison operators. Visual Basic provides various operators that can be used in appropriate types of comparisons.

Boolean Variables
The Boolean data type is used to declare a variable whose value would be set as true (1) or false (0). To declare such a value, you use the Boolean keyword. The variable can then be initialized with a starting value. The Boolean constant is used to check that the state of a variable (or a function) is true or false. You can declare such a variable as: dim GotThePassingGrade as Boolean; Later in the program, for a student who got a failing grade, you can assign the other value, like this GotThePassingGrade = False;

Logical Operators
Equality =
To compare two values for equality, use the = operator. Its formula is: Value1 = Value2 The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our formula, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false or 0.

Here is an example: Private Sub Command1_Click() Dim value As Integer value = 15 Text1.Text = "Comparison of Value = 32 produces " & (value = 32) End Sub

The result of a comparison can also be assigned to a Boolean variable. Here is an example: Private Sub Command1_Click() Dim value1 As Integer Dim value2 As Boolean value1 = 15 value2 = (value1 = 32) Text1.Text = "Comparison of Value = 32 produces " & value2 End Sub

Logical Not
When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. To render a variable unavailable during the evolution of a program,

apply the logical not operator which is Not. Its formula is: Not Value There are two main ways you can use the logical Not operator. As we will learn when studying conditional statements, the most classic way of using the logical Not operator is to check the state of a variable. To nullify a variable, you can write Not to its left. When used like that, you can display its value. You can even assign it to another variable. Here is an example: Private Sub Command1_Click() Dim value1 As Integer Dim value2 As Boolean value1 = 250 value2 = Not value1 Text1.Text = value2 End Sub When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it. This is done by typing Not to its left.

Inequality <>
Visual Basic provides an operator used to compare two values for inequality. Its formula is: Value1 <> Value2 <> is a binary operator (like all logical operators except the logical Not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 <> Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value.

Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean

value1 = 212 value2 = -46 value3 = (value1 <> value2) Text1.Text = value1 & " <> " & value2 & " = " & value3 End Sub

The inequality is obviously the opposite of the equality.

Less Than <


To find out whether one value is lower than another, use the < operator. Its formula is: Value1 < Value2 The value held by Value1 is compared to that of Value2. As it would be done with other operations, the comparison can be made between two variables, as in Variable1 < Variable2. If the value held by Variable1 is lower than that of Variable2, the comparison produces a true or positive result.

Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean

value1 = 212 value2 = -46 value3 = (value1 < value2) Text1.Text = value1 & " < " & value2 & " = " & value3 End Sub

Less Than Or Equal <=


The previous two operations can be combined to compare two values. This allows you to know if two values are the same or if the first is less than the second. The operator used is <= and its formula is: Value1 <= Value2 The <= operation performs a comparison as any of the last two. If both Value1 and Value2 hold the same value, the result is true or not null. If the left operand, in this case Value1, holds a value lower than the second operand, in this case Value2, the result is still true.

Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean

value1 = 212 value2 = -46 value3 = (value1 <= value2) Text1.Text = value1 & " <= " & value2 & " = " & value3 End Sub

Greater Than >


When two values of the same type are distinct, one of them is usually higher than the other. Visual Basic provides a logical operator that allows you to find out if one of two values is greater than the other. The operator used for this operation uses the > symbol. Its formula is: Value1 > Value2 Both operands, in this case Value1 and Value2, can be variables or the left operand can be a variable while the right operand is a constant. If the value on the left of the > operator is greater than the value on the right side or a constant, the comparison produces a true or positive value. Otherwise, the comparison renders false or null. This can be illustrated as follows:

Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean

value1 = 212 value2 = -46 value3 = (value1 > value2)

Text1.Text = value1 & " > " & value2 & " = " & value3 End Sub

Greater Than or Equal >=


The greater than or the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. Its formula is: Value1 >= Value2 A comparison is performed on both operands: Value1 and Value2. If the value of Value1 and that of Value2 are the same, the comparison produces a true or positive value. If the value of the left operand is greater than that of the right operand, the comparison produces true or positive also. If the value of the left operand is strictly less than the value of the right operand, the comparison produces a false or null result. This can be illustrated as follows:

Here is an example:

Private Dim Dim Dim

Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean

value1 = 212 value2 = -46 value3 = (value1 >= value2)

Text1.Text = value1 & " >= " & value2 & " produces " & value3 End Sub

Here is a summary table of the logical operators we have studied: Operator Meaning Example Opposite = Equality to a=b <> <> Not equal to 12 <> 7 = < Less than 25 < 84 >= <= Less than or equal to Cab <= Tab > > Greater than 248 > 55 <= Greater than or equal >= Val1 >= Val2 < to

Previous

Copyright 2005 FunctionX, Inc.

Next

Conditional Statements
Overview of Conditions
Introduction
The essence of computer programming relies on telling the computer what to do when something occurs, and how to do it. This is performed by setting conditions, examining them and stating what decisions the computer should make. Microsoft Visual Basic uses various conditional statements for almost any situation your computer can encounter. As the application developer, it is up to you to anticipate these situations and make your program act accordingly.

Practical Learning: Using an If...Then Statement


1. Start Microsoft Visual Basic and accept to use Standard EXE by pressing Enter

2. Right-click the form and click View Code

The If...Then Statement


The If...Then statement examines the truthfulness of an expression. Structurally, its formula is: If ConditionToCheck Then Statement Therefore, the program examines a condition, in this case ConditionToCheck. This ConditionToCheck can be a simple expression or a combination of expressions. If the ConditionToCheck is true, then the program will execute the Statement. There are two ways you can use the If...Then statement. If the conditional formula is short enough, you can write it on one line, like this: If ConditionToCheck Then Statement If there are many statements to execute as a truthful result of the condition, you should write the statements on alternate lines. Of course, you can use this technique even if the condition you are examining is short. In this case, one very important rule to keep is to terminate the conditional statement with End If. Here is an example: If ConditionToCheck Then Statement End If Here is another example: If Condition Then Statement1 Statement2 Statementn End If

Practical Learning: Using an If...Then Statement


1. In the Code Editor, click the arrow of the Object combo box and select Form 2. Click the arrow of the Procedure combo box and select Click 3. Implement the events as follows: Private Sub Form_Click() If BackColor = vbRed Then BackColor = vbBlue End Sub Private Sub Form_Load() BackColor = vbRed End Sub 4. Press F5 to test the application 5. Click somewhere in the form to change its color

6. After using the form, close it and return to MSVB

The If...Then...Else Statement


The If...Then statement offers only one alternative: to act if the condition is true. Whenever you would like to apply an alternate expression in case the condition is false, you can use the If...Then...Else statement. The formula of this statement is: If ConditionToCheck Then Statement1 Else Statement2 End If When this section of code is executed, if the ConditionToCheck is true, then the first statement, Statement1, is executed. If the ConditionToCheck is false, the second statement, in this case Statement2, is executed.

Practical Learning: Using an If...Then...Else Statement


1. To use the new condition, change the form's Click event as follows: Private Sub Form_Click() If BackColor = vbRed Then BackColor = vbBlue Else BackColor = vbRed End If End Sub 2. Press F5 to test the application 3. Click the form a few times to change its color 4. Close the form and return to MSVB

The If...Then...ElseIf Statement


The If...Then...ElseIf statement acts like the If...Then...Else expression, except that it offers as many choices as necessary. The formula is: If Condition1 Then Statement1 ElseIf Condition2 Then Statement2 ElseIf Conditionk Then Statementk End If The program will first examine Condition1. If Condition1 is true, the program will execute Statment1 and stop examining conditions. If Condition1 is false, the program will examine Condition2 and act accordingly. Whenever a condition is false, the program will continue examining the conditions until it finds one. Once a true condition has been found and its statement executed, the program will terminate the conditional examination at End If.

There is still a possibility that none of the stated conditions is true. In this case, you should provide a "catch all" condition. This is done with a last Else section. The Else section must be the last in the list of conditions and would act if none of the primary conditions is true. The formula to use would be: If Condition1 Then Statement1 ElseIf Condition2 Then Statement2 ElseIf Conditionk Then Statementk Else CatchAllStatement End If

Practical Learning: Using an If...Then Statement


1. To use the new expression, change the form's Click event as follows: Private Sub Form_Click() If BackColor = vbRed Then BackColor = vbBlue ElseIf BackColor = vbBlue Then BackColor = vbGreen ElseIf BackColor = vbGreen Then BackColor = vbBlack Else BackColor = vbRed End If End Sub 2. Test the application 3. Close it and return to MSVB

The Select Case Statement


If you have a large number of conditions to examine, the If...Then...Else will go through each one of them. Visual Basic offers the alternative of jumping to the statement that applies to the state of the condition. The formula of the Select Case is: Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case Expressionk Statementk End Select

The Expression will examined and evaluated once. Then it will compare the result of this examination with the Expression of each case. Once it finds one that matches, it would execute the corresponding Statement. If you anticipate that there could be no match between the Expression and one of the Expressions, you can use a Case Else statement at the end of the list. The statement would then look like this: Select Case Expression Case Expression1 Statement1 Case Expression2 Statement2 Case Expressionk Statementk Case Else Statementk End Select

Practical Learning: Using a Select Case Statement


1. To use a Select Case expression, change the form's Click event as follows: Private Sub Form_Click() Select Case BackColor Case vbRed BackColor = vbBlue Case vbBlue BackColor = vbGreen Case vbGreen BackColor = vbBlack Case Else BackColor = vbRed End Select End Sub 2. Test the application then close it

Loops Repeaters
Introduction
A loop is an expression used to repeat an action. Visual Basic presents many variations of the loops and they combine the Do and the Loop keywords.

The Do...While Loop


The formula of the Do... While loop is: Do While Condition Statement(s) Loop

This expression examines the Condition. If the condition is true, then it executes the Statement or statements. After executing the statement(s), it goes back to examine the Condition. AS LONG AS the Condition is true, the Statement will be executed and the Condition will be tested again. If the Condition is false or once the condition becomes false, the statement will not be executed and the the program will move on. As you may guess already, the Condition must provide a way for it to be true and to be false.

The Do...Loop...While Statement


Since the Do...While statement tests the Condition first before executing the Statement, sometimes you will want the program to execute the Statement first, then go back and test the Condition. Visual Basic offers a reverse to the formula, which is: Do Statement(s) Loop While Condition In this case, the Statement or Statements will be executed first. Then the Condition will be tested. If the Condition is true, the program will execute the Statement again. The program will continue this examination-execution as long as the Condition is true. The big difference here is that even if the Condition is false, the program will have executed the Condition at least once.

The Do...Until...Loop Statement


An alternative to the Do...While loop is the Do...Until loop. Its formula is: Do Until Condition Statement(s) Loop This loop will first examine the Condition, instead of examining whether the Condition is true, it will test whether the Condition is false.

The Do...Loop...Until Statement


An alternative to the Do...Until...loop consists of executing the the Statement first. The formula is: Do Statement(s) Loop Until Condition This express executes the Statement first. After executing the Statement, it would examine the Condition. If the Condition is False, then it would go back and execute the Statement again and re-check the Condition. Once the Condition becomes true, it would stop and move on; but as long as the Condition is False, the Statement would be executed.

Loop Counters

Introduction
The looping statements we reviewed above are used when you don't know or can't anticipate the number of times a condition needs to be checked in order to execute a statement. If you know with certainty how many times you want to execute a statement, you can use another form of loops that use the For...Next expression.

The For...To...Next Loop


One of the loop counters you can use is For...To...Next. Its formula is: For Counter = Start To End Statement(s) Next Used for counting, the expression begins counting at the Start point. Then it examines whether the current value (after starting to count) is greater than End. If that's the case, it then executes the Statement(s). Next, it increments the value of Counter by 1 and examines the condition again. This process goes on until the value of Counter becomes equal to the End value. Once this condition is reache, the looping stops.

Stepping the Counting Loop


The formula above will increment the counting by 1 at the end of each statement. If you want to control how the incrementing processes, you can set your own, using the Step option. Here is the formula: For Counter = Start To End Step Increment Statement(s) Next Counter You can set the incrementing value to your choice. If the value of Increment is positive, the Counter will be added its value. This means that you can give it a negative value, in which case the Counter will be subtracted the set value.

For Each Item In the Loop


Since the For...Next loop is used to execute a group of statements based on the current result of the loop counting from Start to End, an alternative is to state various steps in the loop and execute a group of statements for each one of the elements in the group. This is mostly used when dealing with a collection of items. The formula is: For Each Element In Group Statement(s) Next Element The loop will execute the Statement(s) for each Element in the Group.

Logical Operators

Introduction
A logical operation is one that is performed on one or two expressions to check the truthfulness or falsity. Logical operators are performed only on conditional statements.

Logical Conjunction: AND


A logical conjunction is an operation used to check two conditions for absolute truthfulness. This operation uses the AND keyword. The formula to use the AND operator is Condition1 AND Condition2 The left condition, Condition1, is first checked. If it is False, the whole expression is rendered False and the checking process stopped. If the left condition is True, then the right condition, Condition2, is checked. If the right condition is False, the whole expression is False, even if the first is True. In the same way, if both conditions are false, the whole expression is False. Only if both conditions are True is the whole condition true. This can be resumed as follows:

Condition1 False Don't Care True

Condition2 Don't Care False True

Condition1 AND Condition2 False False True

Logical Disjunction: OR
A logical disjunction is performed on two conditions for a single truthfulness. This operation uses the OR keyword on the following formula: Condition1 OR Condition2 The left condition, Condition1, is first checked. If Condition1 is True, then the whole expression is true, regardless of the outcome of the second. If Condition1 is False, then Condition2 is checked. If Condition2 is True, the whole expression is True even if Condition1 is False. In the same way, if both conditions are True, the whole expression is True. The whole expression is false only if both Condition1 and Condition2 are False. This can be resumed as follows: Condition1 True Don't Care True False Condition2 Don't Care True True False Condition1 OR Condition2 True True True False

Details on Conditional Statements


Mixed And Nested Conditional Statements

Sometimes you will find out that one conditional statement does not satisfy the criteria you are trying to apply to your program; you might have to have many conditions. Programming allows you to use as many conditions as necessary and to create some conditions inside of others. Mixing conditions is the ability to use different conditional statements in your program. Nesting is the ability to put some conditions inside of others. These two techniques make your programs more efficient.

Built-in Logical Constants: NULL


A variable is said to be null when its value is invalid or doesn't bear any significant or recognizable value.

Built-in Logical Constants: TRUE and FALSE


An expression is said to be false if the result of its comparison is 0. Otherwise, the expression is said to bear a true result.

Previous

Copyright 2002-2005 FunctionX, Inc.

Next

Modules, Functions and Procedures


Introduction to Modules and Procedures
Introduction
A module is a file, also called a source file (as in C/C++, Pascal, and other languages) that belongs to a program and in which you write code. For example, while we were using forms so far, we couldn't write code on a form. We had to access the Code Editor.

Practical Learning: Introducing Modules

1. Start Visual Basic and, in the opening dialog box, double-click Standard EXE 2. To save the project, on the main menu, click File -> Save Project 3. Locate your MS Visual Basic folder created in the first lesson and display it in the Save In combo box

4. In the Save File As dialog box, click the Create New Folder button 5. Type Modules1 and press Enter twice to display the new folder in the Save In combo box 6. Replace the name of the file in the File Name edit box with Main and press Enter 7. Type Modules1 to replace the name of the project and press Enter. If are asked whether
you want to add the project to SourceSafe, click No 8. Display the form and design it as follows:

Control Label TextBox Label TextBox Button Label TextBox Button 9. Save all

Name

Caption Side:

Additional Properties Alignment: 1-Right Justify Alignment: 1-Right Justify

txtSide

0.00 Perimeter:

txtPerimeter

0.00

cmdCalcPerimeter Calculate Area: txtArea cmdCalcArea 0.00 Calculate Alignment: 1-Right Justify

Creating a Module
There are two main ways you obtain a module for your program. When you create a form, a module is automatically created and associated to it. You can access the module of a form by right-clicking it and click View Code. Besides the modules created for your forms, you can create your own modules any time. To create a new module, on the main menu, you can click Project -> Add Module. In the Add Module dialog box, you can click Open. Once a new module

has been added to your project, it is treated as a file. As such, you should save it to give it a friendlier name. The name of a module can be used to indicate the type of code included in that module. Once a module is ready, you can type any piece of valid code in it. Such a module is automatically made available to other parts of your program. Just as you can write code in a module attached to a form, you can also write code in an independent module (unlike some other languages like C/C++ or Pascal, you usually don't need to reference one module from another; once a module has been created, you can use its contents as you wich). Any existing module of your project is represented in the Project window with a button and a name in the Modules node. Therefore, to open a module, in Project window, you can doubleclick its node.

Practical Learning: Creating a Module


1. To access the form's module, double-click anywhere in the form and notice that a source file opens

2. To create a new module, on the Standard toolbar, click the arrow of the Add Form button
and click Module

3. In the Add Module dialog box, make sure the Module icon is selected and click Open

4. To save the new module, on the Standard toolbar, click the Save button 5. Change the name of the file to modGeometry and press Enter 6. To change the name of the module in Visual Basic, in the Project window, click Module1.
In the Properties window, click (Name). Type Routines and press Enter

Procedures
A procedure is an assignment you ask the compiler to take care of inside of your program. The assignment is performed behind the scenes. The program developer writes the function and the user would only see the result. In reality, there are two types of procedures you will use in your programs: those that have already been created thus made available to you, and those you will create yourself. In Visual Basic, like most other languages, there are two categories of procedures: functions and sub routines (many other languages like Pascal make this distinction; some other languages like C++, C#, etc use only the name function to identify both categories).

Sub Routines
Introduction
As mentioned already, there are differences between a function and a sub routine. A sub routine is an assignment that is carried but doesn't give back a result. To create a sub routine, start by typing the Sub keyword followed by a name because, like everything else, a procedure must have a name. The name of a procedure is always followed

by parentheses. At the end of the sub routine, you must type End Sub. Therefore, the syntax of a sub routine is: Sub ProcedureName() End Sub You can also initiate a sub routine by asking Visual Basic to generate one for you. To do that, on the main menu, you can click Tools -> Add Procedure... In the Add Procedure dialog box, specify a name for the procedure. Make sure the Sub radio button is selected and click OK. The name of a procedure should follow the same rules we learned to name the variables, omitting the prefix: If the procedure performs an action that can be represented with a verb, you can use that verb to name it. Here are examples: show, display To make the name of a procedure stand, you should start it in uppercase. Examples are Show, Play, Dispose, Close You should use explicit names that identify the purpose of the procedure. If a procedure would be used as a result of another procedure or a control's event, reflect it on the name of the sub procedure. Examples would be: afterupdate, longbefore. If the name of a procedure is a combination of words, you should start each word in uppercase. Examples are: AfterUpdate, SayItLoud

The section between the Sub and the End Sub lines is referred to as the body of the procedure. The body of the procedure is used to define what and how the assignment should be carried. For example, if you need to use a variable, you can declare it and specify what kind of variable you need. There is no restriction on the type of variables that can be declared in a procedure. Here is an example in which a string variable is declared in the body of a sub routine: Sub Assignment() Dim strFullName As String End Sub In the same way, you can declare as many variables as you need inside of a procedure. The actions you perform inside of a procedure depend on what you are trying to accomplish. For example, a procedure can simply be used to create a string. The above procedure can be changed as follows: Sub Assignment() Dim strFullName As String strFullName = "Paul Bertrand Yamaguchi" End Sub

Practical Learning: Creating a Sub Procedure


1. To create a new sub procedure, in the Routines file, type sub SquarePerimeter and
press Enter. This produces: Sub SquarePerimeter()

End Sub 2. To create another sub routine, on the main menu, click Tools -> Add Procedure...

3. In the Name edit box, type SquareArea

4. Click OK 5. Implement both routines as follows: Sub SquarePerimeter() Dim dblSide As Double Dim dblPerimeter As Double dblSide = Form1.txtSide dblPerimeter = dblSide * 4 Form1.txtPerimeter.Text = dblPerimeter End Sub Public Sub SquareArea() Dim dblSide As Double Dim dblArea As Double dblSide = Form1.txtSide dblArea = dblSide * dblSide Form1.txtArea.Text = dblArea End Sub 6. Save all

Calling a Sub Routine


Once you have sub routine, whether you created it or it shipped with Visual Basic, you can use it. Using a procedure is also referred to as calling it. Before calling a procedure, you should first locate the section of code in which you want to use it. For example, you may want to use it inside of a control's event. To call a simple sub routine, simply type its name in the section where you want to use. For example, you can call the assignment in the Load event of a form as follows:

Private Sub Form_Load() Assignment End Sub

Practical Learning: Calling a Sub Procedure


1. Display the form

2. Double-click the top Calculate button and, in its body, type SquarePerimeter 3. Double-click the bottom Calculate button and, in its body, type SquareArea
Private Sub cmdCalcArea_Click() SquareArea End Sub Private Sub cmdCalcPerimeter_Click() SquarePerimeter End Sub

4. Text the application

5. Close the form and return to MSVB

Functions
Introduction
Like a sub routine, a function is used to perform an assignment. The main difference between a sub routine and a function is that, after carrying its assignment, a function gives back a result. We also say that a function "returns a value". To distinguish both, there is a different syntax you use for a function.

Practical Learning: Introducing Modules


1. Display the form and change its design as follows:

Control Label TextBox Label TextBox Button Label TextBox Label TextBox 2. Save all

Name

Caption Length:

Additional Properties Alignment: 1-Right Justify Alignment: 1-Right Justify

txtLength

0.00 Height:

txtHeight

0.00 Calculate Perimeter:

txtPerimeter

0.00 Area:

Alignment: 1-Right Justify Alignment: 1-Right Justify

txtArea

0.00

Function Creation
To create a function, you use the Function keyword followed by a name and parentheses. Unlike a sub routine, because a function returns a value, you should/must specify the type of value the function will produce. To give this information, on the right side of the closing parentheses, type the As keyword, followed by a data type. To indicates where a function stops, type End Function. Based on this, the minimum syntax used to create a function is: Function FunctionName() As DataType End Function The name of a function follows the same rules and suggestions we reviewed for sub routines. The DataType factor indicates the type of value that the function will return. If the function will produce a word or a group of words, you can create it as String. If the function will check something and determine whether it produce a true or a false value, you can create it as Boolean. The other data types are also valid in the contexts we reviewed them. As mentioned already, the section between the Function and the End Function lines is the body of the function. It is used to describe what the function does. As done on a sub routine, one of

the actions you can perform in a function is to declare a (local) variable and use it as you see fit. Here is an example: Function CallMe() As String Dim Salute As String Salute = "You can call me Al" End Function After performing an assignment in a function, to indicate the value it returns, somewhere after the assignment and before the End Function line, type the name of the function, followed by the = sign, followed by the value the function returns. Here is an example in which a function returns a name: Function CallMe() As String CallMe = "You can call me Al" End Function You can also use some local variables in the function to perform an assignment and then assign their result to the name of the function. Here is an example: Function CallMe() As String Dim Salute As String Salute = "You can call me Al" CallMe = Salute End Function

Practical Learning: Creating a Function


1. Display the Routines module and delete (only) the previously implemented routines

2. To create a new function, at the end of the file, type function RectPerimeter and press
Enter 3. To create another function, on the main menu, create Tools -> Add Procedure...

4. In the Name edit box, type RectArea 5. In the Type section, click Function

6. Press Enter

7. Implement both functions as follows: Function RectPerimeter() Dim dblLength As Double Dim dblHeight As Double dblLength = Form1.txtLength.Text dblHeight = Form1.txtHeight.Text RectPerimeter = (dblLength + dblHeight) * 2 End Function Public Function RectArea() Dim dblLength As Double Dim dblHeight As Double dblLength = Form1.txtLength.Text dblHeight = Form1.txtHeight.Text RectArea = dblLength * dblHeight End Function 8. Save all

Calling a Function
As done for the sub routines, in order to use a function in your program, must call it. Like a sub routine, to call a function, you can simply type its name in the desired section of the program. Here is an example: Private Sub Form_Load() CallMe End Sub Since the primary purpose of a function is to return a value, to better take advantage of such a value, you can assign the name of a function to a property or a variable in the section where you are calling the function. In the following example, the return value of the CallMe function is assigned to the Caption property of the form from its own Load event: Private Sub Form_Load() Caption = CallMe End Sub

Practical Learning: Calling a Function


1. Display the form and double-click the Calculate button 2. Implement its event as follows: Private Sub cmdCalculate_Click() txtPerimeter = RectPerimeter txtArea = RectArea End Sub 3. Test the application

Arguments and Parameters


Introduction
So far, to use a value in a procedure, we had to declare it. In some cases, a procedure may need an external value in order to carry its assignment. A value that is supplied to a procedure is called an argument. When creating a procedure that will use an external value, declare the argument that represents that value between the parentheses of the procedure. For a sub routine, the syntax you use would be: Sub ProcedureName(Argument) End Sub If you are creating a function, the syntax would be: Function ProcedureName(Argument) Function Sub The argument must be declared as a normal variable, omitting only the Dim keyword. Here is

an example that creates a function that takes a string as argument: Function CalculatePayroll(strName As String) As Double Function Sub A certain procedure can take more than one argument. In this case, in the parentheses of the procedure, separate the arguments with a comma. Here is an example of a sub routine that takes two arguments: Sub EvaluateInvoice(strEmplName As String, dblHourlySalary As Currency) End Sub In the body of a procedure that takes one or more arguments, use the argument(s) as you see fit as if they were locally declared variables. For example, you can involve them with values inside of the procedure. You can also exclusively use the values of the arguments to perform the assignment.

Practical Learning: Passing Arguments to a Procedure


1. To pass arguments to a function, change the functions in the Routines module as follows: Function RectPerimeter(dblLength As Double, dblHeight As Double) RectPerimeter = (dblLength + dblHeight) * 2 End Function Public Function RectArea(dblLength As Double, dblHeight As Double) RectArea = dblLength * dblHeight End Function 2. Save

Passing Arguments (By Value)


To call a procedure that takes an argument, type its name and a space, followed by value for each argument. The value provided for an argument is also called a parameter. If there is more than one argument, separate them with a comma. Here is an example: Private Sub txtResult_GotFocus() Dim dblHours As Double Dim dblSalary As Double dblHours = txtHours dblSalary = txtSalary CalcAndShowSalary dblHours, dblSalary End Sub Sub CalcAndShowSalary(Hours As Double, Salary As Double) Dim dblResult As Double dblResult = Hours * Salary

txtResult = dblResult End Sub Alternatively, you can use the Call keyword to call a sub routine. In this case, when calling a procedure using Call, you must include the argument(s) between the parentheses. using Call, the above GotFocus event could call the CalcAndShowSalary as follows: Private Sub txtResult_GotFocus() Dim dblHours As Double Dim dblSalary As Double dblHours = txtHours dblSalary = txtSalary Call CalcAndShowSalary(dblHours, dblSalary) End Sub If you use the above technique to call a procedure that takes more than one argument, you must provide the values of the arguments in the exact order they are listed inside of the parentheses of the function. Fortunately, you don't have to. If you know the name of the arguments, you can type them in any order and provide a value for each. To do that, on the right side of each argument, type the := operator followed by the desired value for the argument. Here is an example: Function DisplayName(FirstName As String, LastName As String) As String Dim FullName As String FullName = FirstName & " " & LastName DisplayName = FullName End Function Private Sub Form_Load() Caption = DisplayName(LastName:="Nguyen", FirstName:="Hermine") End Sub

Practical Learning: Passing Arguments by Value


1. Display the form and double-click the Calculate button 2. To call the above functions, change the button's event as follows: Private Dim Dim Dim Dim Sub cmdCalculate_Click() dblLen As Double dblHgt As Double dblPerim As Double dblArea As Double

dblLen = txtLength.Text dblHgt = txtHeight.Text dblPerim = RectPerimeter(dblLen, dblHgt) dblArea = RectArea(dblLen, dblHgt) txtPerimeter.Text = dblPerim txtArea.Text = dblArea

End Sub

3. Test the application

4. Close the form and return to MSVB

Passing Arguments By Reference


When calling a procedure that took an argument, we were supplying a value for that argument. When this is done, the procedure that is called makes a copy of the value of the argument and make that copy available to calling procedure. That way, the argument itself is not accessed. This is referred to as passing an argument by value. This can be reinforced by typing the ByVal keyword on the left side of the argument. Here is an example: Sub GetFullName(ByVal FullName As String) FullName = "Nguyen, Hermine" End Sub If you create a procedure that takes an argument by value and you have used the ByVal keyword on the argument, when calling the procedure, you don't need to use the ByVal keyword; just the name of the argument is enough, as done in the examples on arguments so far. Here is an example: Private Sub Form_Load() Dim FName As String FName = "Albert Edou Nkoulou" GetFullName FName Caption = FName End Sub This would produce:

An alternative to this technique is to pass the address of the argument to the called procedure. When this is done, the called procedure doesn't receive a simple copy of the value of the argument: the argument is accessed at its root. That is, at its memory address. With this technique, any action carried on the argument will be kept. That is, if the value of the argument is modified, the argument would now have the new value, dismissing or losing the original value it had. This technique is referred to as passing an argument by reference. To pass an argument by reference, on its left, type the ByRef keyword. This is done only when creating the function. When the called procedure finishes with the argument, the argument would keep whatever modification was made on its value. Now consider the following: Private Sub Form_Load() Dim FName As String FName = "Albert Edou Nkoulou" GetFullName FName Caption = FName End Sub Sub GetFullName(ByRef FullName As String) FullName = "Nguyen, Hermine" End Sub This would produce:

Using this technique, you can pass as many arguments by reference as many arguments by value as you want. As you may already, this technique is also used to make a sub routine return a value, which a regular sub routine cannot do. Furthermore, passing arguments by reference allows a procedure to return as many values as possible while a regular function can return only one value.

Practical Learning: Passing Arguments by Reference


1. Display the Routines module 2. To pass an argument by reference, change the RectArea function as follows: Function RectPerimeter(ByVal dblLength As Double, _ ByVal dblHeight As Double) RectPerimeter = (dblLength + dblHeight) * 2 End Function Sub RectArea(ByVal dblLength As Double, _ ByVal dblHeight As Double, _ ByRef dblSurface As Double) dblSurface = dblLength * dblHeight End Sub 3. Display the module of the form and change the Click event of the Calculate button as follows: Private Dim Dim Dim Dim Sub cmdCalculate_Click() dblLen As Double dblHgt As Double dblPerim As Double dblArea As Double txtLength.Text txtHeight.Text = RectPerimeter(dblLen, dblHgt) dblLen, dblHgt, dblArea

dblLen = dblHgt = dblPerim RectArea

txtPerimeter.Text = dblPerim txtArea.Text = dblArea End Sub 4. Test the application 5. Close the form

Previous

Copyright 2001-2005 FunctionX, Inc.

Next

Built-In Functions
Overview of Built-In Procedure
Introduction
A procedure is referred to as "built-in" if it shipped with your language. To make your job a little easier, Microsoft Visual Basic comes equipped with many functions that you can use right away in your program. Based on this, before creating your own function, first check whether the functionality you are looking is already implementing in one of the available procedures because those that ship with Visual Basic are highly reliable and should be preferred. Before using a built-in procedure, you must of course be familiar with it. This comes either by consulting the documentation or by experience. This means that you must know its name, its argument(s), its return value, and its role.

Conversion Functions
The first action you should take when dealing with a value or an expression is to convert it to the appropriate type. There are various conversion functions adapted to the different possible kinds of values. The general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or value the user would have entered in a form. It could also be the result of a calculation performed on another field or function. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax.

The conversion functions are as follows:

Function Name CBool CByte CDate CDbl CInt CCur CLng CSng CStr Return Type Boolean Byte Date Double Integer Currency Long Single String Description Converts an expression into a Boolean value Converts an expression into Byte number Converts and expression into a date or time value Converts an expression into a flowingpoint (decimal) number Converts an expression into an integer (natural) number Converts an expression into a currency (monetary) value Converts an expression into a long integer (a large natural) number Converts an expression into a flowingpoint (decimal) number Converts an expression into a string

Practical Learning: Using Conversion Functions


1. Start a new project and create a form as follows:

2. Here are the names of the controls (the three left labels provided "as is"): (Name) Caption (Name) frmOperations Operations fraOperations lblMainTitle Algebraic Operations optAddition txtNumber1 optSubtraction

and the horizontal lines are Caption Operations Addition Subtraction

txtNumber2 txtResult

Result

optMultiplication Multiplication optDivision Division

3. On the Project window, click the View Code button

4. On the Object combo box, select optAddition. 5. Since its default event is Click, implement it as follows: 6. Private Sub optAddition_Click() 7. Dim dblNumber1 As Double 8. Dim dblNumber2 As Double 9. Dim dblResult As Double 10. 11. dblNumber1 = CDbl(txtNumber1.Text) 12. dblNumber2 = CDbl(txtNumber2.Text) 13. dblResult = dblNumber1 + dblNumber2 14. 15. txtResult.Text = dblResult End Sub 16. Implement the Click event of the other option buttons the (exact) same way, only changing the sign in the dblResult line. Here is the code: 17. Private Sub optDivision_Click() 18. Dim dblNumber1 As Double 19. Dim dblNumber2 As Double 20. Dim dblResult As Double 21. 22. dblNumber1 = CDbl(txtNumber1.Text) 23. dblNumber2 = CDbl(txtNumber2.Text) 24. dblResult = dblNumber1 / dblNumber2 25. 26. txtResult.Text = dblResult 27. End Sub 28. 29. Private Sub optMultiplication_Click() 30. Dim dblNumber1 As Double 31. Dim dblNumber2 As Double 32. Dim dblResult As Double 33. 34. dblNumber1 = CDbl(txtNumber1.Text) 35. dblNumber2 = CDbl(txtNumber2.Text) 36. dblResult = dblNumber1 * dblNumber2 37. 38. txtResult.Text = dblResult 39. End Sub 40. 41. Private Sub optSubtraction_Click() 42. Dim dblNumber1 As Double 43. Dim dblNumber2 As Double 44. Dim dblResult As Double 45. 46. dblNumber1 = CDbl(txtNumber1.Text) 47. dblNumber2 = CDbl(txtNumber2.Text) 48. dblResult = dblNumber1 - dblNumber2 49. 50. txtResult.Text = dblResult End Sub

51. To test the form, press F5. 52. Please, make sure you type a number, and a number other than 0, in the Second Number text box, especially before clicking the Division option button. This is because we didn't write a conditional statement that would check the content of those text boxes, and we know that it is "nasty" to divide a number by 0. Conditional statements will be studied later: one lesson at a time

String-Based Functions
Introduction
A string-based function is one that deals with functions; either it manipulates them or returns them. Microsoft Visual Basic allows you to be specific about the return value you are expecting. Some of the functions you will be using can be configured to return exactly a string. Such functions use the $ suffix that states it clearly.

Message Boxes
A message box is a special form used to display a piece of information to the user. As opposed to a regular form, the user cannot type anything on the box. There are usually two kinds of dialog boxes you will create: one that simply displays information and one that expects the user to make a decision. To create a message box, you can use the MsgBox function. There are two techniques to use it. To display a simple message with just an OK button, use the MsgBox method whose syntax is MsgBox Message The parameter, Message, is the string to present to the user. As a normal, it should be passed in double-quotes. Here is an example: Private Sub Form_Load() MsgBox "Welcome to the wonderful world of Microsoft Visual Basic" End Sub When the above version of the the MsgBox function is used, a rectangular form (we will learn later on that this type of form is called a dialog box) is presented to the user, display a string message and an OK button:

Another version of the MsgBox function allows you to present a message that asks a question to the user, expecting a decision. This version displays a more informative prompt with more than one button. The user makes a decision by clicking one of the presented buttons. After the user has clicked a button, you can then retrieve the result and use it as you see fit. The syntax

of this version is: MsgBox Message, [Buttons], [Title], [HelpFile], [Context] The Message argument is the string that the user will see displaying on the message box. As a string, you can display it in double quotes. You can also create it from other pieces of strings. The Message argument can be made of up to 1024 characters. To display the Message on multiple lines, you can use either the constant vbCrLf or the combination Chr(10) & Chr(13) between any two strings. Besides the Message parameter, this version allows you to display more than one button. If you don't need to, you don't have to specify the buttons. If you don't, the message box would appear with only an OK button. Otherwise, you can specify what buttons to display. This is done using the Buttons argument. There are different kinds of buttons available and Visual Basic recognizes them by a numeric value assigned to each. The buttons are Button vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel Value 0 1 2 3 4 5 Display

Here is an example of a message box that display a Yes and a No buttons: Private Sub Form_Load() MsgBox "Are you ready to rumbleeeeeeeeeee", vbYesNo End Sub This would produce:

When a message box displays more than one button, one of the buttons usually has a thick button. That button is also called the default button. If the user presses Enter upon reading the message, the compiler would behave as if the default button was clicked. There are some buttons that are set automatically as default when you create the message box. If you don't like the set button to be the default, you can specify which one you prefer as default. To do that combine a second value with one of the above values for the buttons. You can set the default argument using the following table Option Value

Parent Controls
Characteristics of Parent Controls
Introduction
An object is referred to as parent when it can carry or host other objects, acting as their parent. When you start the computer, the first object the operating system creates is the desktop window. This is a wide rectangular area that covers the entire monitor screen. Based on the settings of the Control Panel, the operating system uses either a color or a picture (a bitmap) to fill the window. Once the desktop is ready, other objects or controls can be placed on it. The desktop is the parent of all other objects that display on the screen. To provide some information about the desktop, you can use an object called Screen. This allows you to get such details as the screen dimensions (its width and height), the form that is displaying on the screen, the list of fonts in the computer, etc. A control is referred to as container if it can host other controls. While the desktop is the main container of the computer, to develop your applications, you will use your own controls that can act as parent to other controls. Examples of such controls include the form, the frame, the picture box, the status bar, the toolbar, etc. The list is impressive and these parent controls are usually used for different purposes. In fact, the only real characteristic they share is their ability to host other controls. Except for the form (and consequently the dialog box), most, if not all, of the other containers must be hosted by a form. Therefore, after starting a project or once you get a form, you can place a control container on it (the form). Once placed on a form, these parent windows can host their own controls. Therefore, to use a container, you can either position your control on the form, in which case the form would act as the parent, or you can first select one of the containers, place it on a form, and then add other controls to it.

The Parents Location


Except for the desktop window, every visual object either on the screen or in your application must be located. The location of an object depends on its parent and some other considerations. The main object or frame of an application, which is usually the first form of a project, when it appears on the screen, is located with regards to the screen. Such a form is located on a

Cartesian coordinate system whose origin is on the top-left corner of the screen. The horizontal axis moves from the left border to the right. The vertical axis moves from the top border down. The distance from the left border of the screen to the left border of the form is called the Left property. The distance from the top border of the screen to the top border of the form is its Top property. This can be illustrated as follows: The above illustration shows a form positioned on a monitor. The desktop acts as the parent window of the form. In the same way, if you place a control on a container, the control is located with regards to its parent, not based on the screen. As seen previously, in such a case, the origin of the coordinate system is located on the top-left corner of the parent window. The distance from the left border of the parent window to the left border of the control is the controls Left property. The distance from the top border of the parent window to the top border of the control is the controls Top property. Here is an example in which a control as a child is positioned inside of another control that acts as its parent:

The Client Area


An object positioned on a parent can be seen only if its dimensions are confined to the body of the parent. To manage the display of visible windows, each parent provides a section called the client area. For the desktop screen, the client area is the whole screen. For a form, the client area is the body of the form without the title bar. Most other containers provide their whole

body as the client area:

The desktop window provides a rectangular area that it can use to display the computers applications. This area is also used to host other objects. Although an objects borders can span beyond the borders of the desktop, only the area of an object covered by the desktop can be seen. Here is an example of a window whose right side cannot be seen:

The client area is a rectangle primarily used for its location and dimensions. To get the values of the shape that compose the client area, you have various options and considerations. For example, to get the area that represents the desktop, which would let you know how much real estate is available for your application, you can call the Screen.Width and/or Screen.Height variables. It is important to know where the origin of a control is located. During control design, we saw that, when a container is selected and you double-click a visual control on the Toolbox, the new control would be added to the container. On the other hand, if you have a container that is positioned on the form but the container, or any specific container, is not selected, if you double-click a control on the Toolbox, the control would be added to the form even though the new control may be positioned on a container. In this case, the form would become the parent of the new control. Therefore, in order to do anything related to the location and/or dimensions of a control, you must know the coordinate of the origin used as the basis for its location and dimensions. Because only a parent can host some controls, it holds an origin and makes it available to its children.

Forms

Introduction
A form is a rectangular object that can be used as a program of its own, it is also usually used as part of a bigger application. The form is a window control that mostly serves as a place holder for other controls. There are two main ways you create a form: as its own program or as part of an application. Whenever you launch Microsoft Visual Basic, the opening dialog offers to create a form. To add a form into an existing program, on the main menu, you can click Project -> Add Form. When creating a form, you can control its properties at design time using the Properties window. Many of these properties can be set at run time with code. A form can control its own properties when an event related to a form is fired. A form's properties can also be set or changed using other controls on the form itself or controls from another form or from the computer (for example, you can control a property based on the system time of the computer).

Practical Learning: Starting a Form


1. Start Microsoft Visual Basic. When the opening dialog box comes up, make sure Standard EXE is selected and press Enter

2. To change the name of the form, in the Properties window, click (Name) and type frmMain
3. To test the application, press F5

4. After viewing it, close it using its system Close button

Forms Characteristics: The System Icon


As the main or primary object of an application, a form is equipped with a title bar. This can be used to minimize, maximize, restore, move, or close a form. The most left section of a form's title bar displays a small picture called an icon. A Visual Basic form displays a default icon. If you want to use a different icon, you must have one in file. You can either use one of the icons that ship with Microsoft Visual Studio or design your own. To display a different icon on the title bar of a form, first select the form. Then, in the Properties window, click the ellipsis button of the Icon property. This would open the Load Icon dialog box to let you locate and select an icon. After selecting an icon, you can click Open.

Forms Characteristics: The Caption


On the right side of a form's system icon, the title bar displays what is referred to as the name of the window: this is the caption. After adding a form to a project, it displays a default caption that mimics its name. For example, the first form is called Form1 and its caption is Form1. Most of the time, it will be necessary to change the caption so it displays a friendlier name. To change the caption of a form, after selecting it in the design, in the Properties window, click Caption and either change the text or edit the existing one.

Forms Characteristics: The System Buttons

On the right side of its title bar, a form displays three system buttons. The presence of this group of buttons is controlled by the ControlBox Boolean property whose default value is True. Therefore, if you don't want any these buttons at all, you can set the ControlBox property to False. If you keep or set it to True, you can then configure different combinations that control the presence or availability of these buttons. When the ControlBox property is set to True, you can control the system buttons using the MinButton and the MaxButton properties.

The Startup Position of a Form


When you create an application that has a form, the form is positioned in a design window that hosts it. When the application is executed and the form comes up, you should be able to predict where it would be positioned on the screen, since its position on the design window has nothing to do with its actual position at run time. There are various ways you can specify the default position of a form when its application launches. To manually and visually specify where a form would be positioned when it comes up, while it is selected in design, in the lower right section of the screen, click and drag the same rectangle in the Form Layout window:

This technique allows you to position the form with a good approximation. Alternatively, after selecting the form in design, in the Properties window, change the value of the StartUpPosition property. The options are: StartUpPosition 0 - Manual Description Allows you to specify the position of the form using the rectangle in the Form Layout window If this is the first or main form, its parent is the desktop. Therefore it would be positioned in the center of the screen. If this is the second form, it would be positioned in the center of the form used to display it This form will be centered with regards to the desktop The application will let the operating system specify the position of the form

1 - CenterOwner

2 - CenterScreen 3 - Windows Default

As another solution, you can double-click the form to access its Load event, then assign a value to the Left and the Top properties of the form. This is the least precise and the most complicated of all three solutions because you should know the system of measures you are using.

Practical Learning: Configuring a Form


1. Click the from to make sure it is selected

2. Click the BorderStyle field and change it to 3 - Fixed Dialog 3. Again on the Properties window, click Caption and type Interactions With Controls 4. Click Height and type 2800 5. Change the StartUpPosition field to 2 - CenterScreen 6. Click Width and type 3200
7. To save this program, on the main menu, click File -> Save Project. 8. From the Save File As dialog box, click the arrow to the Save In combo box and select My Documents.

9. Click the Create New folder button


10. Type VBExo Forms Interaction

11. Double-click VBExo Forms Interaction to display it in the Save In combo box. 12. Accept the name of the form as frmControls. Click Save. 13. When prompted to provide a name for the project, type prjFormsInteractions and press Enter. If prompted to add your project to Source Safe, click No.

14. To test the form, on the Standard toolbar, click the Start button
15. Notice that at runtime, a form's appearance changes. Notice also that the form is centered on the screen when it starts.

16. After viewing the form, to stop it, on the Standard toolbar, click the End button
17. A form's properties can also be set with code. Double-click the center of the form to access one of the form's events. 18. Notice that the event is the Load event. This is the default event of a form. 19. Change the listing of the Load event as follows: 20. Private Sub Form_Load() 21. Me.Height = 4500 22. Me.Width = 6465 23. Me.Caption = "Form Interaction" End Sub

24. To test the form, press F5


25. Notice that the form opens with different dimensions than those set in the Properties window. The form used the dimensions and the caption set in the Load event.

26. After viewing the form, to close it, click its Close button
27. Notice that the form is back to the dimensions set in the Properties event.

28. To use another event, on the Project window, click the View Code button 29. In the Code window, make sure that Form is displaying in the Object combo box.
Click the arrow of the Procedure combo box and select DblClick:

30. Write the code of the DblClick event as follows: 31. Private Sub Form_DblClick() 32. Me.Caption = "You double-clicked Me!" End Sub 33. To test the form, on the main menu, click Run -> Start. 34. After viewing the form, to close it, on the main menu, click Run -> End.

35. To add another form to the project, on the Standard toolbar, click the Add Form button

36. From the Add Form dialog box, make sure the Form icon is selected and make sure the check box is not checked. Click Open.

37. As the new form is displaying, in the Properties window, click (Name) and type
frmEmployees

38. Double-click BorderStyle a few times (it should take only one double-click) until it
displays 3 - Fixed Dialog

39. Click Caption and type Employees Records 40. We will display this form when the user double-click in the center (or an empty area) of
the first form. In the Project window, double-click frmControls

41. In the Code window, make sure that Form is displaying in the Object combo box. Change the code of the DblClick event as follows: 42. Private Sub Form_DblClick() 43. Me.Caption = "You double-clicked Me!" 44. frmEmployees.Show End Sub

45. To save the project, on the main menu, click File -> Save Project.

46. To test the project, on the Standard toolbar, click the Start button
47. To display the other form, double-click in the displayed form. 48. Notice that the other form displays.

49. To close the form, click the End button


50. On the main menu, click Window -> Project1 - frmControls (Form). 51. In the Properties window, click Height and type 4000 52. Click Width and type 5000

Frames

A frame is used as a place holder for other controls; therefore, it is called a container. You can insert any kind of control in a frame, including labels, text box, command buttons, and even other controls. The controls inside of a frame are treated as a group; as we will see, some of their settings can be changed together at once.

Practical Learning: Creating A Frame 1. To create a new project, on the main menu, click File -> New Project. If you are asked to save the current project, click No. 2. On the New Project dialog box, click Standard EXE and click OK. 3. Change the form's size to 4875 x 4725. 4. Change the the Border Style to 3 - Fixed Dialog 5. On the Toolbox, double-click Label 6. On the Properties Window, make the following changes: (Name) Alignment Caption Font lblMainTitle Height 2 - Center Left College Park Auto Parts Top Times New Roman, Bold, 16 495 120 120 4335

7. On the Toolbox, double-click Frame 8. On the Properties window, make the following changes: (Name) fraMake Top 720

Caption Height Left

Make 1575 120

Visible Width

True 2055

9. To test the form, press F5

10. To close the running form, click its close button

Previous

Copyright 2001-2004 FunctionX, Inc.

Next

Primary Controls
Microsoft Visual Basic
Command Buttons
A command button is a control that allows the user to make a decision based on what the form is displaying. This could be a simple acknowledgement such as a form displaying a quick message to the user. It could also require the user to make other selections or perform some settings on a dialog box before continuing to other issues. As a programmer, the computer and the user count on you to decide on the role of a button. And as stated already, a button can assume any role you assign it to.

Practical Learning: Inserting A Command Button


1. On the Toolbox, double-click the CommandButton 2. On the Properties window, make the following changes: (Name) Caption Height cmdEmployees Employees 375 Left Top Width 120 3120 1215

3. To test the form, press F5 (of course, the button doesn't do much because we didn't ask it to do anything). 4. There are many ways you can access the area where you will be writing code. Usually, the code you write will be associated with one of the controls on your form. Although many behaviors are associated with each control, every control, including the form itself, has a

default behavior. For example, the default behavior of a button is the click action. To access the code associated with the first button, double-click Employees. This opens the Code Editor window. 5. Notice that the mouse cursor is inside of the click event code associated with the cmdEmployees button. Change the code of the event as follows: 6. Private Sub cmdEmployees_Click() 7. frmEmployees.Show End Sub

8. To test the effect of the new code, on the Standard toolbar, click the Start button
9. When the main form is loaded, click the Employees button. Notice that the second displays.

10. To close the Employees Records form, click its Close button
11. Notice that the caption did not change on the main form, although it would change if you had double-clicked inside of the form.

12. To close the main form, click its Close button


13. On the Toolbox, double-click CommandButton.

14. On the Properties window, make the following changes: (Name) Caption Height cmdExit Exit 375 Left Top Width 3480 3120 1215

15. Earlier you saw that when a form is loaded, if you click the End button

on the Standard toolbar, the form is closed. Now, we will write code that will tell Microsoft Visual Basic that when we click the Exit button, we want it to behave as if we had clicked the End button on the Standard toolbar. On the main form, double-click the Exit button.

16. Press Tab and type End so your code appears as follows:
17. Private Sub cmdExit_Click() 18. End End Sub

19. To test the functionality of the form as this time, on the Standard toolbar, click the Start
button 20. Click the Employees button

21. To close the Employees Records form, click its close button
22. To close the main form, click Exit.

23. To save the project, on the main menu, click File -> Save Project

Labels
A label is a control used to display text on a form. This control is for two main purposes: to provide quick information or to help the user identify another control on the form. The properties of a label are completely under your control; the user cannot manipulate them. Although you can change these properties at will, make sure you set their appropriate values in the Properties window. Always avoid distracting the user.

Practical Learning: Creating A Label 1. To create a new project, on the main menu, click Filed -> New Project 2. On the opening dialog box, make sure Standard EXE is selected and click Open. 3. On the Toolbox, click Label. 4. On the form, draw a rectangular box from the top left section to the right section.

5. On the Properties window, click (Name) and type lblFormTitle


6. Click the Alignment field, click the arrow of its combo box and select 2 - Center

7. Click Caption and type Rockville Auto-Mart 8. Click the Font field. Click its Build button 10. Click Height and type 495 11. Click Left and type 120 12. Click Top and type 120 13. Click Width and type 4500 14. To test the form, press F5 15. To close the running form, click its close button
16. On the Toolbox, double-click Label. 17. Using the label's handles, move it under the main title and on the left. 18. By double-clicking and moving the controls, create the following four labels: (Name) Caption Height Left Top Width lblFirstName First Name 255 120 705 855 lblLastName LastName 255 120 1125 855 lblFullName Full Name 255 120 1560 855 lblMessage Empty 255 120 2160 3975 . to call the Font dialog box.

9. On the Font dialog box, set the font to Times New Roman, Style = Bold, and Size = 22.

19. To test the form, press F5.

20. After viewing the form, click Close button

Text Boxes
A text box is used to receive information from the user by her typing it into this box. A text box can also be used to simply display information to the user. Although a text box is a good control by itself, it usually doesn't mean much to the user if she doesn't know what the box is used for. Therefore, you should always create a text box in conjunction with a label. The label is used to identify what the text is used for. You should position the label on the left or on top of the text box. The rules of using the computer suggest that a text box be identified by the caption of its label. For example, if a label displays First Name:, the text box on its right would be called The First Name Text Box. If a labels displays How Old Are You?, its corresponding text box would be called The How Old Are You Text Box. But remember, programmatically, the text box and its label are completely independent. Practical Learning: Adding A Text Box 1. On the Toolbox, double-click TextBox. 2. On the form, drag the text box up a little bit to move it up. 3. By double-clicking, add three more boxes. 4. On the Properties window, make the following changes (Name) Height Left Text Top Width txtFirstName 285 1080 Empty 705 1815 txtLastName 285 1080 Empty 1125 1815 txtFullName 285 1080 Empty 1560 1815

5. To test the form, press F5.

6. To close the running form, click its close button

Introduction To Expressions
The contents of controls are worth nothing unless you put them to good use. This is done through expressions. An expression is a combination of values and signs that allow you to get a new value to display in a control. This is handy because some values will simply not be available when the user is using your program. For example, to get a sum of two numbers that the user is supposed to enter in a form, when creating such a form, you cannot know what the user would enter in two boxes, but you can write an expression that would use whatever the user enters, to get a new value. The values involved in an expression could be external to the program, such as algebraic numbers; they could also come from the program itself, such as BillingRate or DateHired; and they could be a combination of algebraic numbers and controls content on the your program. An operation, an expression, are the result of a function is usually meant to be displayed in a

new and appropriate control.

Option Buttons
Sometimes referred to as radio buttons, option buttons allow the user to select one item in a group. We have already seen that controls are placed on a form before being used in an application. The controls on a form are considered in a group. A frame allows you to create a group in a group. This is particular useful when you want to use option buttons in your program. You should create a group of these buttons so that the user can select one.

Practical Learning: Creating Option Buttons 1. On the Toolbox, click the OptionButton control. 2. On the form, click and drag inside of the frame. For this exercise, you don't need to be precise when dragging but make sure you draw only inside of the frame.

3. On the Properties window, change the name of the option button to optFord and change
its caption to Ford 4. From the Toolbox, draw another OptionButton inside of the frame but under the first option button.

5. Change the name of the new option button to optHonda and its caption to Honda
6. From the Toolbox, draw another check box inside of the frame but under the second option button.

7. Change the name of the new option button to optBMW and its caption to BMW
8. To test the form, press F5

9. To close the running form, click its close button

Check Boxes
Check Boxes allow to user to make selections by click these boxes. The user knows that a choice is made when a check mark appears inside of the corresponding square. Programmatically, a check box specifies a value as being true or false. Although they are usually treated as a group, the user can select more than one check box or as many as are available. As you will see in your programming experience, the functionality of check boxes can be very easy or very complex, depending on the result you are trying to achieve.

Practical Learning: Creating Check Boxes 1. On the Toolbox, click Frame

2. On the form, click on the right section of the form but outside of the existing frame and drag right a little bit. 3. On the Properties window, make the following changes: (Name) Caption Height Left fraFord Ford 1575 2280 Top Visible Width 720 True 2055

4. On the Toolbox, click the CheckBox. 5. On the form, click and drag inside of the right frame. For this exercise, you don't need to be precise when dragging but make sure you draw only inside of the right frame. 6. On the Properties window, change the name of the check box to chkFocus and change its caption to Focus. 7. From the Toolbox, draw another check box inside of the left frame but under the first check box. 8. Change the name of the new check box to chkEscort and its caption to Escort 9. From the Toolbox, draw another check box inside of the left frame but under the second check box. 10. Change the name of the new check box to chkTaurus and its caption to Taurus 11. To test the form, press F5

12. To close the running form, click its close button

Previous

Copyright 2001-2004 FunctionX, Inc.

Next

List-Based Controls
Combo Boxes
Introduction
A combo box is a window control that presents a list of items the user can select from. Visually, a combo box looks like a text box equipped with a down pointing arrow on its right side. By default, a combo box displays an item. In order to change the content of that box,

different options are available. You cam allow the user to type in the combo box and try to match what the user types with one of the items in the list. You can also make the user only select an item from the list by clicking the down pointing arrow. You can also display the list at all times and let the user select an item from the list. If the list is long and cannot display everything at the same time, a combo box is equipped with a vertical scroll bar. To create a combo box, from the Toolbox, you can (1) double-click it or (2) click it once and draw on the form. Once you have a combo box on your form, it is important that you change its name to a more meaningful one. One of your first concerns with combo boxes is to decide what it will display or what it will be used for. Then provide a list of its items. When designing a combo box, you can use the List field to provide a list of its items. This allows you to create a list of items you know already. To create such a list, click the arrow of the List field, type an entry, press Ctrl + Enter, type the next item, and continue like that until you have provided the items desired. To programmatically create a list of items for a combo box, first decide when the list should be filled up, using one of the events. Then use the AddItem method to create the necessary list. Most of the time, you will decide to fill a list when the form Loads.

Practical Learning: Using a Combo Box


1. Start Microsoft Visual Basic and create a new project 2. On the Properties window, change the (Name) of the form to frmTimeSheet 3. Set the BorderStyle of the form to 3 - Fixed Dialog. 4. Change the Caption of the form to Employees Time Sheet 5. On the Toolbox, double-click the Label control 6. In the Properties window, change the Caption to Monday 7. Move the new label to the upper left corner of the form. 8. On the Toolbox, double-click the ComboBox control

9. On the Properties window, change the name of the combo box to cboMondayIn
10. Click the List field. Notice an arrow of its combo box. Click that arrow.

11. Click in the empty and type 08:00 AM 12. Press Ctrl + Enter and type 08:30 AM 13. Press Ctrl + Enter and type 09:00 AM 14. Press Ctrl + Enter and type 09:30 AM 15. Use the same technique to add 10:00 AM, 10:30 AM, 11:00 AM, 11:30 AM, 12:00 PM,
12:30 PM, 01:00 PM, 01:30 PM, 02:00 PM, 03:00 PM, 03:30 PM, 04:00 PM, 04:30 PM, 05:00 PM, 05:30 PM, 06:00 PM, 06:30 PM, 07:00 PM, 07:30 PM, and 08:00 PM.

16. Still in the Properties window for the combo box, delete the content of the Text field. 17. Move the combo box to the right side of the Monday label.

18. To test the form, press F5


19. Notice that the combo box doesn't display any item. Click the arrow of the combo box to display its list. 20. To close the form, click its Close button. 21. On the form, click the combo box to select it.

22. On the Properties window, click the Text field, type 09:00 AM and press Enter. 23. On the form, right-click the combo box and click Copy. 24. Right-click an empty area of the form and click Paste.
25. You receive a message box asking whether you want to create an array of controls. Click No. 26. Drag the pasted combo box and position it on the right side of the first combo box.

27. While the new combo box is still selected, in the Properties window, change its name to
cboMondayOut 28. Click the arrow of its List field. Notice that since we copied it instead of creating from scratch, this combo box inherited the list from the original combo box.

29. Change its Text field to 05:00 PM


30. Click the Monday label on the form to select it. 31. Press Delete to delete that label.

32. On the Toolbox, click the ComboBox control.


33. On the form, draw a combo box on the left side of the left combo box, enough to contain a name such as Saturday.

34. On the Properties window, change the name of the new combo box to cboWeekdays
35. Double-click an empty area of the form to access the form's load event. 36. Implement the event as follows: 37. Private Sub Form_Load() 38. cboWeekdays.AddItem "Sunday" 39. cboWeekdays.AddItem "Monday" 40. cboWeekdays.AddItem "Tuesday" 41. cboWeekdays.AddItem "Wednesday" 42. cboWeekdays.AddItem "Thursday" 43. cboWeekdays.AddItem "Friday" 44. cboWeekdays.AddItem "Saturday" 45. cboWeekdays.Text = "Monday" End Sub

46. To test the form, press F5 47. To close the running form, click its close button
.

List Boxes

A list is a control that presents a list of items to the user who can make his selection by clicking on the list. Depending on how the list is configured, the user can click one item at a time or select many items from the list.

Practical Learning: Creating A List Box 1. Create a new Standard EXE project 2. Give the form a size of 4800 x 2715

3. From the Properties section, click the (Name) box and type frmCountries 4. Change the the Border Style to 3 - Fixed Dialog and its Caption to Type Country Selection
5. From the Toolbox, click ListBox. 6. On the form, draw a box from 120, 120 to 2055 x 2010. 7. In the Properties section, click the (Name) and type lstCountry 8. Scroll down and click ToolTip Text. Type Double-click a country 9. From the Components toolbar, click the TextBox. 10. On the form, draw a box from 2400,120 to 2055 x 375 11. Scroll up in the Properties and click Name. Type txtCountry 12. Scroll down in the properties list and click in the Text field. delete the content of that Text field 13. From the Components toolbar, click the CommandButton 14. On the form, draw a box from 2400, 120 to 2055 x 375 15. In the Properties section, click the (Name) field and type cmdCountryChoice

16. Click the Caption field and type &Choose A Country


17. Double-click an empty area of the form, for example under the command button. That will call the Editor window and launch the Form Load event. 18. To add items in a list box you use the AddItem method associated with the listbox object. The AddItem method uses two arguments, the first one is the string item that you want to display in the list, the second is the order index you want the items to follow. The second argument is optional, if you don't provide it, Visual Basic will follow you presented the list. Edit the Form Load event to look as follows: 19. Private Sub Form_Load() 20. lstCountry.AddItem "United States" 21. lstCountry.AddItem "Cote D'Ivoire" 22. lstCountry.AddItem "Costa Rica" 23. lstCountry.AddItem "Saudi Arabia" 24. lstCountry.AddItem "Thailand" 25. lstCountry.AddItem "Greece" 26. End Sub 27. We will let the user click an item in the list then click the command button to display the selected item in the text box. 28. Click the Object combo box and select cmdCountryChoice. That launches the default event

for a command button which is the Click event, because that's what users mainly do to a button. 29. Edit the Click event as follows: 30. Private Sub cmdCountryChoice_Click() 31. txtCountry.Text = lstCountry.Text End Sub 32. Click the Object combo box and select lstCountry. That initializes the events for the list box. 33. The default event of the list box is the Click because that is the first thing users think of doing on a list box. In this case we would like to get a double-clicked item from the user and display the double-clicked item in the text. All we need to do is ask the double-clicked list box to behave as if the cmdCountryChoice Click the Procedure combo box and select DblClick 34. Edit the Double Click procedure as follows 35. Private Sub lstCountry_DblClick() 36. cmdCountryChoice.Value = True End Sub 37. To test the form, on the Standard toolbar, click the Start button 38. Double-click Costa Rica. Double-click Greece. Notice that the country double-clicked displays in the text box. 39. Click Thailand, then click the button. Click Cote D'Ivoire and click the button. Notice that this action has the same effect as double-clicking the country.

40. To test the form, press F5 41. To close the running form, click its close button
.

Previous

Copyright 2001-2004 FunctionX, Inc.

You might also like