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.
  11. The Options dialog is made of various property sheets. Click the Editor Format property 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

    Options Dialog Box
  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. Parent MenuA 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.

  1. 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.

    Tool Tip
  2. Move the mouse to another button and read the tool tip.
  3. To experiment with one of the button, on the Standard toolbar, click the Start button Start. Notice that the form runs in its execution state.
  4. To stop the running form, on the Standard toolbar, click the End button End.
  5. 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.
  6. Without clicking, move the mouse to the arrow of the first button on the toolbar, the Add Standard EXE Project button.
  7. To dismiss the menu, click the arrow of the same menu.
  8. 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.
  9. The Toolbox provides the necessary tools to create your applications.
     

Microsoft Visual Basic Toolbox

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.

  1. 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.
  2. Click the Caption field and type: Time Sheet
  3. The Project Explorer window gives a list of the forms and modules that are part of the current project.
     

Project

To experiment with the Project Explorer window, click the Toggle Folders button Toggle Folder. Notice that the folders are collapsed.

To expand the folders, click the Toggle Folders button again.

  1.  
  2. Still on the Project Explorer window, click View Code. You are presented with the Code Editor window.
  3. To send the Code Editor window to the background again, on the Project Explorer window, click the View Object button View Object.
     
  4.  

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.

Form Layout

  1.  
  2. Drag the small rectangle in the Form Layout screen again and position it to the middlw of the small screen.
  3. To verify the result, press F5 to run the form. Notice that the running form displays in the center of the screen.
  4. 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 Create New Folder
  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 Create New Folderagain
  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
     
    Save As
  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

 

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

 

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):
     

Form

  1. 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 right-click 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:

Client Area Coordinate Origin

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:

Control Location

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
  1. Press F5 to test the application
     
  2. 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

North - South

Shrinks or heightens the control

Cursor

Resizes the control in North-East <-> South-West direction

Widens or narrows

Narrows or widens the control

North West / South East

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 text-based 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.

 

 

 

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
     

  1. Press Enter
  2. Notice that Visual Basic added the parentheses and the End Sub line
  3. In the Code window, notice that the Object combo box is displaying Form
  4. Click the arrow of the Object combo box to display its list: 
     

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

  1. Notice the section of the MouseDown event. Also notice that this event has a few arguments
  2. We will eventually learn what the writings of these arguments mean.
    In the Object combo box, notice that Text1 is still displaying.
  3. In the Code window, click on one of the form events.
  4. 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:
 

 

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
  1. Press F5 to test the application. Notice that it appears red
  2. 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:
     

  1. Press F5 to test the application
  2. Notice that you receive an error:
     
  3. Click OK
  4. On the Standard toolbar, click the End button
  5. Change the Load event as follows:
     
Private Sub Form_Load()
    Dim BackgroundColor
    
    BackgroundColor = vbRed
    
    BackColor = BackgroundColor
End Sub
  1. After using the form, close it and return to MSVB
  2. Click the arrow of the Procedure combo box and select Click
    • 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 ranges from 0 to 255. A variable of byte type can be used to hold small values such as a person's age, the number of fingers on an animal, etc.

To declare  a variable for a small number, use the Byte keyword. Here is an example:

Private Sub Form_Load()
    Dim StudentAge As Byte
End Sub

 

Integer

 

 

An integer is a natural number larger than the Byte. It can hold a value between 
-32,768 and 32,767. Examples of such ranges are: the number of pages of a book.

To declare a variable of type integer, use the Integer keyword. Here is an example:

Private Sub Form_Load()
    Dim MusicTracks As Integer
End Sub

Long Integer

 

 

A long integer is a natural number whose value is between –2,147,483,648 and 2,147,483,642. Examples are the population of a city, the distance between places of different countries, the number of words of a book.

To declare a variable that can hold a very large natural number, use the Long keyword. Here is an example:

Private Sub Form_Load()
    Dim Population As Long
End Sub

Decimal Data Types

 

 

Introduction

 

 

A real number is one that displays a decimal part. This means that the number can be made of two sections separated by a symbol that is referred to as the Decimal Separator or Decimal Symbol. This symbol is different by language, country, group of languages, or group of countries. In US English, this symbol is the period as can be verified from the Regional (and Language) Settings of the Control Panel of computers of most regular users:

Regional Options

On both sides of the Decimal Symbol, digits are used to specify the value of the number. The number of digits on the right side of the symbol determines how much precision the number offers.

 

 

Single

 

 

A single is a decimal number whose value can range from –3.402823e38 and –1.401298e-45 if the number is negative, or 1.401298e-45 and 3.402823e38 if the number is positive.

To declare a variable that can hold small decimal numbers with no concern for precision, use the Single data type. Here is an example:

Private Sub Form_Load()
    Dim CountryName As String
    Dim IsMarried As Boolean
    Dim StudentAge As Byte
    Dim Tracks As Integer
    Dim Population As Long
    Dim Distance As Single
End Sub

Double

 

 

While the Single data type can allow large numbers, it offers less precision. For an even larger number, Microsoft Visual Basic provides the Double data type. This is used for a variable that would hold numbers that range from 1.79769313486231e308 to –4.94065645841247e–324 if the number is negative or from 1.79769313486231E308 to 4.94065645841247E–324 if the number is positive.

To declare a variable that can store large decimal numbers with a good level of precision, use the Double keyword.

 

In most circumstances, it is preferable to use Double instead of Single when declaring a variable that would hold a decimal number. Although the Double takes more memory spaces (computer memory is not expensive anymore(!)), it provides more precision.

Here is an example of declaring a Double variable:

Private Sub Form_Load()
    Dim Distance As Double
End Sub

Currency

 

 

The Currency data type is used for a variable that can hold monetary values. To declare such a variable, use the Currency keyword. Here is an example:

Private Sub Form_Load()
    Dim CountryName As String
    Dim IsMarried As Boolean
    Dim StudentAge As Byte
    Dim Tracks As Integer
    Dim Population As Long
    Dim Distance As Single
    Dim StartingSalary As Currency
End Sub

Other Data Types

 

 

Date

 

 

A date is a numeric value that represents the number of days that have elapsed since a determined period. A time is a numeric value that represents the number of seconds that have elapsed in a day.

To declare a variable that can hold either date values, time values, or both, use the Date keyword. After the variable has been declared, you will configure it to the appropriate value. Here are two examples:

Private Sub Form_Load()
    Dim CountryName As String
    Dim IsMarried As Boolean
    Dim StudentAge As Byte
    Dim Tracks As Integer
    Dim Population As Long
    Dim Distance As Single
    Dim StartingSalary As Currency
    Dim DateOfBirth As Date
    Dim KickOffTime As Date
End Sub

Object

 

 

An Object is almost anything else that you want to use in your program. If you don't specify a data type or can't figure out what data type you want to use, you can use the Variant keyword or let Visual Basic use the Variant data type.

 

Variant

 

 

A Variant can be used to declare any kind of variable. You can use a variant when you can't make up your mind regarding a variable but, as a beginning programmer, you should avoid it.

Here is a table of various data types and the amount of memory space each one uses:

 

 

Data type

Description

Range

Byte

1-byte binary data

0 to 255

Integer

2-byte integer

– 32,768 to 32,767

Long

4-byte integer

– 2,147,483,648 to 2,147,483,647

Single

4-byte floating-point number

– 3.402823E38 to – 1.401298E – 45 (negative values)

1.401298E – 45 to 3.402823E38 (positive values)

Double

8-byte floating-point number

– 1.79769313486231E308 to
– 4.94065645841247E – 324 (negative values)

4.94065645841247E – 324 to 1.79769313486231E308 (positive values)

Currency

8-byte number with fixed decimal point

– 922,337,203,685,477.5808 to 922,337,203,685,477.5807

String

String of characters

Zero to approximately two billion characters

Variant

Date/time, floating-point number, integer, string, or object.

16 bytes, plus 1 byte for each character if a string value.

Date values: January 1, 100 to December 31, 9999

Numeric values: same range as Double

String values: same range as String Can also contain Error or Null values

Boolean

2 bytes

True or False

Date

8-byte date/time value

January 1, 100 to December 31, 9999

Object

4 bytes

Any Object reference

 

Using Variables

 

 

Details on Declaring Variables

 

 

We have learned how to declare a variable as follows:

Dim CountryName As String

We also saw that we can declare different variables each on its own line as follows;

Dim FirstName As String
Dim LastName As String
Dim Salary As Currency
Dim AlreadyVisited As Boolean

If you have many variables of the same data type, you can declare them on the same line, each separated with a comma. Remember to specify their common type. Here is an example:

Private Sub Form_Load()
Dim CountryName, Address, City, State As String
Dim IsMarried As Boolean
Dim StudentAge As Byte
Dim Tracks As Integer
Dim Population As Long
Dim Distance As Single
Dim StartingSalary, WeeklyEarnings As Currency
Dim DateOfBirth, KickOffTime As Date
End Sub

When naming your variables, besides the above suggestions, you can start a variable's name with one to three-letter prefix that could identify the data type used. Here are a few suggestions:

 

 

Data Type

Prefix

Example

Boolean

bln

blnFound

Byte

byt

bytTracks

Date/Time

dtm

dteStartOfShift

Double

dbl

dblDistance

Error

err

errCantOpen

Integer

int

intNbrOfStudents

Long

lng

lngPopulation

Object

obj

objConnection

Single

sng

sngAge

String

str

strCountryName

Currency

cur

curHourlySalary

Variant

var

varFullName

 

Constants

 

 

Introduction

 

 

A constant is a value that doesn't change. There are two types of constants you will use in your programs: those supplied to you and those you define yourself.

 

The Carriage Return-Line Feed Constant

 

 

Visual Basic provides the vbCrLf constant. It is used to interrupt a line of code and move to the next line.

 

Built-in Constants: PI

 

 

PI is a mathematical constant whose value is approximately equal to 3.1415926535897932. It is highly used in operations that involve circles or geometric variants of a circle: cylinder, sphere, cone, etc.

 

 

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

-5

-4

-3

-2

-1

 

1

2

3

4

5

6

 

+∞

   0

-∞

 

-6

-5

-4

-3

-2

-1

 

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

Caption

Name

Label

Number

 

TextBox

 

txtOperand

CommandButton

Operation

cmdOperation

  1. Double-click the Operation button and implement its event as follows:
     
Private Sub cmdOperation_Click()
    txtOperand = +248.64
End Sub
  1. Press F5 to test the application
  2. 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
  1. Press F5 to test the application
  2. 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

Caption

Name

Label

First Name:

 

TextBox

 

txtOperand1

Label

Last Name:

 

TextBox

 

txtOperand2

CommandButton

Addition

cmdAddition

Label

Result:

 

TextBox

 

txtResult

  1. Double-click the Addition button and change its code as follows:
     
Private Sub cmdAddition_Click()
    Dim dblOperand1 As String
    Dim dblOperand2 As String
    Dim dblResult   As String
    
    dblOperand1 = txtOperand1
    dblOperand2 = txtOperand2
    dblResult = dblOperand1 + " " + dblOperand2
    
    txtResult = dblResult
End Sub
  1. Test the application. Enter a name one the First Name text box and another name in the Last Name text box then click Addition
     
  2. 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

Caption

Name

Label

Number 1:

 

TextBox

 

txtOperand1

Label

Number 2:

 

TextBox

 

txtOperand2

CommandButton

Addition

cmdAddition

CommandButton

Subtraction

cmdSubtraction

Label

Result:

 

TextBox

 

txtResult

  1. Double-click the Addition button and change its code as follows:
     
Private Sub cmdSubtration_Click()
    Dim dblOperand1 As Double
    Dim dblOperand2 As Double
    Dim dblResult   As Double
    
    dblOperand1 = txtOperand1
    dblOperand2 = txtOperand2
    dblResult = dblOperand1 - dblOperand2
    
    txtResult = dblResult
End Sub
  1. Test the application. Enter a number one the Number text box and another number in the Number text box then click Subtraction
     
  2. 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 Sub cmdSubtration_Click()
    Dim dblOperand1 As Double
    Dim dblOperand2 As Double
    Dim dblResult   As Double
    
    dblOperand1 = txtOperand1
    dblOperand2 = txtOperand2
    dblResult = dblOperand1 * dblOperand2
    
    txtResult = dblResult
End Sub
  1. Test the application. Enter a number one the Number text box and another number in the Number text box then click Multiplication
     
  2. 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 Sub cmdSubtration_Click()
    Dim dblOperand1 As Double
    Dim dblOperand2 As Double
    Dim dblResult   As Double
    
    dblOperand1 = txtOperand1
    dblOperand2 = txtOperand2
    dblResult = dblOperand1 \ dblOperand2
    
    txtResult = dblResult
End Sub
  1. Test the application. Enter a number one the Number text box and another number in the Number text box then click Division
     
  2. 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. 

 

 

Practical Learning: Using the Decimal Division

 

 

  1. Change the code of the Division button as follows:
     
Private Sub cmdSubtration_Click()
    Dim dblOperand1 As Double
    Dim dblOperand2 As Double
    Dim dblResult   As Double
    
    dblOperand1 = txtOperand1
    dblOperand2 = txtOperand2
    dblResult = dblOperand1 / dblOperand2
    
    txtResult = dblResult
End Sub
  1. Test the application. Enter a number one the Number text box and another number in the Number text box then click Division
     
  2. After using the form, close it
  3. Save all

 

The Exponentiation: ^

 

 

Exponentiation is the ability to raise a number to the power of another number. This operation is performed using the ^ operator (Shift + 6). It uses the following formula:

yx

In Microsoft Visual Basic, this formula is written as:

y^x

and means the same thing. Either or both y and x can be values, variables, or expressions, but they must carry valid values that can be evaluated. When the operation is performed, the value of y is raised to the power of x. 

 

Practical Learning: Using the Exponent Operator

 

 

  1. To start a new application, on the main menu, click File -> New Project...
  2. In the New Project dialog box, double-click Standard EXE
  3. To save the project, on the main menu, click File -> Save Project
  4. Click the Create New Folder button. Type Exponentiation 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

Caption

Name

Label

This number:

 

TextBox

 

txtNumber

Label

to the power of

 

TextBox

 

txtPower

CommandButton

is

cmdCalculate

TextBox

 

txtResult

  1. Double-click the is button and implement its event as follows:
     
Option Explicit
 
Private Sub cmdCalculate_Click()
    Dim dblNumber As Double
    Dim dblPower As Double
    Dim dblResult As Double
    
    dblNumber = txtNumber
    dblPower = txtPower
    dblResult = dblNumber ^ dblPower
    
    txtResult = dblResult
End Sub
  1. Press F5 to test the application. Enter two numbers in the left two text boxes and click the is button
     
  2. After using it, close the form

 

 

The Remainder Operator: Mod

 

 

The division operation gives a result of a number with or without decimal values, which is fine in some circumstances. Sometimes you will want to get the value remaining after a division renders a natural result.

The remainder operation is performed with keyword Mod. Its formula is:

Value1 Mod Value2

The result of the operation can be used as you see fit or you can display it in a control or be involved in another operation or expression.

 

Visual Basic Operators

 

 

Comments

 

 

In the programming world, a comment is a piece of text in Visual Basic code that Visual Basic (in reality the compiler) would not consider when reading your code. As such a comment can be written any way you want.

In Visual Basic, the line that contains a comment can start with a single quote. Here is an example:

 

Private Sub Form_Load()
    ' This line will not be considered as part of the code
End Sub

 

Alternatively, you can start a comment with the Rem keyword. Anything on the right side of rem, Rem, or REM would not be read. Here is an example:

 

Private Sub Form_Load()
    ' This line will not be considered as part of the code
    Rem I can write anything I want on this line
End Sub

 

Comments are very useful and you are strongly suggested to use comments regularly. They can never hurt your code and they don't increase the size of your application. Comments can help you and other people who read your code to figure out what a particular section of code is used for, which can be helpful when you re-visit your code after months or years of not seeing it.

 

The Double Quotes: ""

 

 

A string is an empty space, a character, or a group of characters that you type or provide to a control and you want this character or this group of characters to be considered "as is". In other words, the expression or the control that receives the string should keep it or them the way you supplied it or them unless you give other instructions regarding the string.

A string can be an empty space or one character, such as $ or w; a group of characters, like home or Manchester United or Verbally speaking, I mean… Ah forget it. Most of the time, you will want the program to keep this character or group of characters exactly the way you or the user supplied them. In order to let the program know that this is a string, you must enclose it in double quotes. From our examples, our strings would be "$", "w", "home", "Manchester United", and "Verbally speaking, I mean… Ah forget it".

To assign a string to an expression or a field, use the assignment operator as follows:

Team = "Manchester United"

In the same way, to initialize a variable with a string , use the assignment operator. Here is an example:

Private Sub Form_Load()
    Dim Address As String
    Address = "12404 Lockwood Drive Apt D4"
End Sub

 

The String Concatenator: &

 

 

The & operator is used to append two strings, the contents of two controls, or expressions. This is considered as concatenating them. For example, it could allow you to concatenate a first name and a last name, producing a full name.

The general syntax of the concatenation operator is:

Value1 & Value2

To display a concatenated expression, use the assignment operator on the field. To assign a concatenated expression to a variable, use the assignment operator the same way:

Private Sub Form_Load()
    Dim FirstName, LastName As String
    Dim FullName As String
    
    FirstName = "Francis "
    LastName = "Pottelson"
    FullName = FirstName & LastName
    Text0 = FullName
End Sub

To concatenate more than two expressions, you can use as many & operators between any two strings or expressions as necessary. After concatenating the expressions or values, you can assign the result to another variable or expression using the assignment operator.

 

The Parentheses Operators: ()

 

 

Parentheses are used in two main circumstances: in an event (or procedures, as we will learn) or in an operation. The parentheses in an operation help to create sections in an operation. This regularly occurs when more than one operators are used in an operation.

Consider the following operation: 8 + 3 * 5

The result of this operation depends on whether you want to add 8 to 3 then multiply the result by 5 or you want to multiply 3 by 5 and then add the result to 8. Parentheses allow you to specify which operation should be performed first in a multi-operator operation. In our example, if you want to add 8 to 3 first and use the result to multiply it by 5, you would write (8 + 3) * 5. This would produce 55. On the other hand, if you want to multiply 3 by 5 first then add the result to 8, you would write 8 + (3 * 5). This would produce 23.

As you can see, results are different when parentheses are used on an operation that involves various operators. This concept is based on a theory called operator precedence. This theory manages which operation would execute before which one; but parentheses allow you to completely control the sequence of these operations.

 

The Line Continuation Operator: _

 

 

You will sometimes need to expand your code on more than two lines. This happens regularly if you are writing an expression that involves many entities that must belong to a group.

To continue a piece of code from one line to the next, type an empty space followed by an underscore symbol, then continue your code on the next line.

 

The Period Operator: .

 

 

To access the property of an object, type the name of the object, followed by a period, followed by the name of the property you need. The property you are trying to use must be part of the properties of the object.

If you know the name of the property, you can start typing it. Once the desired property is highlighted, press the Space bar or Tab. If you see the name of the property in the list, you can double-click click it. If the list doesn't appear, press Ctrl + Space bar. If you don't want to use the list displayed by the Code Editor, press Esc. Once you have

 

 

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.
 

 

Equalilty Flowchart

 

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.

 

Flowchart: Not Equal

 

Here is an example:

 

Private Sub Command1_Click()
    Dim value1 As Integer
    Dim value2 As Integer
    Dim 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.
 

 

Flowchart: Less Than

 

Here is an example:

 

Private Sub Command1_Click()
    Dim value1 As Integer
    Dim value2 As Integer
    Dim 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.

 

Flowchart

 

Here is an example:

 

Private Sub Command1_Click()
    Dim value1 As Integer
    Dim value2 As Integer
    Dim 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:

Flowchart

Here is an example:

 

Private Sub Command1_Click()
    Dim value1 As Integer
    Dim value2 As Integer
    Dim 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:

Flowchart: Greater Than Or Equal To

Here is an example:

Private Sub Command1_Click()
    Dim value1 As Integer
    Dim value2 As Integer
    Dim 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 to

Val1 >= Val2

<

 

 

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
  1. Press F5 to test the application
  2. Click somewhere in the form to change its color
  3. 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
  1. Press F5 to test the application
  2. Click the form a few times to change its color
  3. 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
  1. Test the application
  2. 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
  1. 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

Condition2

Condition1 AND Condition2

False

Don't Care

False

Don't Care

False

False

True

True

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

Condition2

Condition1 OR Condition2

True

Don't Care

True

Don't Care

True

True

True

True

True

False

False

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.

 

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 Create New Folder
  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:
     

Geometric Calculations

Control

Name

Caption

Additional Properties

Label

 

Side:

 

TextBox

txtSide

0.00

Alignment: 1-Right Justify 

Label

 

Perimeter:

 

TextBox

txtPerimeter

0.00

Alignment: 1-Right Justify

Button

cmdCalcPerimeter

Calculate

 

Label

 

Area:

 

TextBox

txtArea

0.00

Alignment: 1-Right Justify

Button

cmdCalcArea

Calculate

 

  1. Save all

 

 

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 double-click 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
     
    Adding a New Module
  3. In the Add Module dialog box, make sure the Module icon is selected and click Open
     
    The Add Module dialog box
  4. To save the new module, on the Standard toolbar, click the Save button Save
  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
  1. To create another sub routine, on the main menu, click Tools -> Add Procedure...
  2. In the Name edit box, type SquareArea
     
    Add Procedure
  3. Click OK
  4. 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
  1. 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
  1. Text the application
     
  2. 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

Name

Caption

Additional Properties

Label

 

Length:

 

TextBox

txtLength

0.00

Alignment: 1-Right Justify 

Label

 

Height:

 

TextBox

txtHeight

0.00

Alignment: 1-Right Justify

Button

 

Calculate

 

Label

 

Perimeter:

 

TextBox

txtPerimeter

0.00

Alignment: 1-Right Justify

Label

 

Area:

 

TextBox

txtArea

0.00

Alignment: 1-Right Justify

  1. Save all

 

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
     
    Add Procedure - Creating a 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
  1. 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

 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
  1. 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
  1. 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 Sub cmdCalculate_Click()
    Dim dblLen As Double
    Dim dblHgt As Double
    Dim dblPerim As Double
    Dim 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
  1. Test the application
     
  2. 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
  1. Display the module of the form and change the Click event of the Calculate button as follows:
     
Private Sub cmdCalculate_Click()
    Dim dblLen As Double
    Dim dblHgt As Double
    Dim dblPerim As Double
    Dim dblArea As Double
    
    dblLen = txtLength.Text
    dblHgt = txtHeight.Text
    dblPerim = RectPerimeter(dblLen, dblHgt)
    RectArea dblLen, dblHgt, dblArea
    
    txtPerimeter.Text = dblPerim
    txtArea.Text = dblArea
End Sub
  1. Test the application
  2. Close the form

 

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

Return Type

Description

CBool

Boolean

Converts an expression into a Boolean value

CByte

Byte

Converts an expression into Byte number

CDate

Date

Converts and expression into a date or time value

CDbl

Double

Converts an expression into a flowing-point (decimal) number

CInt

Integer

Converts an expression into an integer (natural) number

CCur

Currency

Converts an expression into a currency (monetary) value

CLng

Long

Converts an expression into a long integer (a large natural) number

CSng

Single

Converts an expression into a flowing-point (decimal) number

CStr

String

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 and the horizontal lines are provided "as is"):

(Name)

Caption

(Name)

Caption

frmOperations

Operations

fraOperations

Operations

lblMainTitle

Algebraic Operations

optAddition

Addition

txtNumber1

 

optSubtraction

Subtraction

txtNumber2

 

optMultiplication

Multiplication

txtResult

Result

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:

Message Box

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

Value

Display

vbOKOnly

0

vbOKCancel

1

vbAbortRetryIgnore

2

vbYesNoCancel

3

vbYesNo

4

vbRetryCancel

5

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:

A Message Box with various buttons

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

vbDefaultButton1 

0

vbDefaultButton2 

256

vbDefaultButton3 

512

vbDefaultButton4 

768

To combine one of these values with one of the buttons, use the OR operator between them. Here is an example:

Private Sub Form_Load()
    MsgBox "Are you ready to rumbleeeeeeeeeee", vbYesNo Or vbDefaultButton2
End Sub

This would produce:

A Message Box with a different default button

These additional buttons can be used to further control what the user can do:

Constant 

Value

Description

vbApplicationModal

0

 

vbSystemModal

4096

 

Besides the message and the button(s), you can also display a friendly icon on the message box. To do that, combine the button value with one of the following:

Icon

Value

Description

vbCritical

16

vbQuestion

32

vbExclamation

48

vbInformation 

64

Here is an example:

Private Sub Form_Load()
    MsgBox "Are you ready to rumbleeeeeeeeeee", vbYesNo Or vbQuestion
End Sub

This would produce:

A Message Box with a friendly icon

As you can see on the message boxes we have used so far, by default, a message box displays the name of the application it belongs to in its title bar. If you want, you can display your own title. This is done using the Title argument which is also called the caption of the message box. It is a string whose word or words you can enclose between parentheses or that you can get from a created string.

If your application is using a help file, you can specify this and let the message box use it. The HelpFile argument is a string that specifies the name of the help file, and the Context argument provides the number that corresponds to the appropriate help topic for the message box.

The way we have been using it so far, the MsgBox is called a method. If you want to use it as a function, that is, if you want it to return a value, you must call it as a function. In other words, its list of arguments must be included in parentheses. The above message can be created as follows:

Private Sub Form_Load()
    MsgBox("Are you ready to rumbleeeeeeeeeee", vbYesNo Or vbQuestion)
End Sub

When treated as a function, MsgBox returns a value. This value corresponds to the button the user clicks on the message box. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox function can return one of the following values:

Button

Return

Value

vbOK

1

vbCancel

2

vbAbort

3

vbRetry

4

vbIgnore

5

vbYes

6

vbNo

7

 

 

Practical Learning: Using Message Boxes

 

 

  1. Create a new Standard EXE project
  2. Design the form as follows:
     

  1. The names of the buttons are btnMessage1, btnMessage2, btnMessage3, btnMessage4, btnMessage5, btnMessage6, btnMessage7, and btnMessage8
    Don't yet save the project.
  2. To start, double-click the Exit button to access its Click event.
  3. Implement it as follows:
6.    Private Sub cmdExit_Click()
7.        Unload Me
8.        End
End Sub
  1. The simplest message box simply displays a message to the user. As an example, double-click the Message 1 button to access its Click event.
  2. Implement it as follows:
11.Private Sub cmdMessage1_Click()
12.    MsgBox "As simple as it can get"
End Sub
  1. To test the form, press F5.
  2. On the form, click the Message 1 button.
  3. Notice that a message box displays. Also notice the caption on the title bar displays Project1.
  4. Click OK to close the message box.
  5. Now, save the project as prjMessages
  6. Test the form again. And click the Message 1 button.
  7. Notice that the caption on the title bar has changed.
  8. Instead of the title bar displaying the name of the project as the caption, you can set your desired caption. This is done through the 3rd argument of the MsgBox function. To see an example, on the form, double-click the Message 2 button. Since the line we want to display is long for our Visual Basic Code Editor window, we will segment it in two lines although it will be displayed on one line only.
  9. Implement it as follows:
22.Private Sub cmdMessage2_Click()
23.    MsgBox "Before formatting a floppy disk, " & _
24.        "make sure you know its content", , _
25.        "Disk Formatting Instructions"
End Sub
  1. To test the form, press F5.
  2. Click the Message 2 button. Notice that the title bar displays an appropriate caption.
  3. Click one of the buttons and close the form.
  4. When creating a message box using the MsgBox function, you can decide which button you want to use, using one of the constants we have listed earlier.
    To see an example, double-click the Message 3 button.
  5. Implement the Click event of the button as follows:
31.Private Sub cmdMessage3_Click()
32.    MsgBox "This will be your only warning", _
33.    vbOKOnly + vbExclamation, _
34.        "Attention! Attention!! Attention!!!"
End Sub
  1. To test the form, press F5.
  2. Experiment with the buttons and see what they display.
  3. To close the running form, click its close button .
  4. If you want to display a message on different lines, you can use the vbCrLf constant. As an example, implement the Click event of the Message 4 button as follows:
39.Private Sub cmdMessage4_Click()
40.    MsgBox "You are about to embark on a long journey." & _
41.        vbCrLf & "If your courage is still fresh, " _
42.        & "please let us know!", _
43.         vbOKCancel + vbQuestion, _
44.         "Accept or Cancel the Mission"
End Sub
  1. Test the form and experiment with the buttons.
  2. Close the form to get back to Visual Basic.
  3. You can also display a message on various lines using the Chr() function. To see an example, implement the Click event of the Message 5 button as follows:
48.Private Sub cmdMessage5_Click()
49.    MsgBox "This message usually appears when trying " & _
50.        "to format a floppy disk while the floppy drive " _
51.        & "is empty. " & Chr(13) & Chr(10) _
52.        & "When or if this happens, make sure you have a " _
53.        & " floppy disk in the floppy drive.", _
54.        vbAbortRetryIgnore + vbCritical, _
55.        "Floppy Disk Formatting"
End Sub
  1. To test the form, press F5.
  2. Close the running form, click its close button Close
  3. The usefulness of the MsgBox function is demonstrated in your ability to perform an action based on the button the user has clicked on the message box function. Indeed, the implementation we have used so far were on the MsgBox method. If you want to get the button that the user has clicked, you have to use the function itself. The true capture of the clicked is revealed by your finding out the clicked button. This is done using conditional statements that we have not learned so far. Therefore, we will just learn how to implement the function and how to assign a response button to it; throughout this tutorial, and whenever necessary, we will eventually see what to do when a certain button has been clicked. To see an example, implement the Click event of the Message 6 button as follows:
59.Private Sub cmdMessage6_Click()
60.    Dim intResponse As Integer
61.    
62.    intReponse = MsgBox("Your printing configuration " _
63.        & "is not fully set." & vbCrLf _
64.        & "If you are ready to print, click" & vbCrLf & _
65.        "(1) Yes: To print the document" & vbCrLf & _
66.        "(2) No: To configure printing" & vbCrLf & _
67.        "(3) Cancel: To dismiss printing", _
68.        vbYesNoCancel + vbInformation, _
69.        "Critical Information")
End Sub
  1. To test the form, press F5.
  2. Close the running form, click its close button Close
  3. When a message box display, one of the buttons, if more than one is displaying, has a thicker border than the other(s); such a button is called the default button. By default, this is the 1st or most left button on the message box. If you want to control which button would be the default, use one of the default constant buttons listed above. To see an example, implement the Click event of the Message 7 button as follows:
73.Private Sub cmdMessage7_Click()
74.    Dim intAnswer As Integer
75.    
76.    intAnswer = MsgBox("Do you want to continue this " _
77.        & "operation?", _
78.        vbYesNoCancel + vbQuestion + vbDefaultButton2, _
79.        "National Inquiry")
End Sub
  1. To test the form, press F5.
  2. Close the running form, click its close button Close.
  3. Although the user cannot type on a message box, not only can you decide what it displays, but you can also use string variables that would be available only when the form is running. We will see a lot of examples throughout this tutorial. But as an example, implement the Click event of the Message button as follows:
83.Private Sub cmdMessage8_Click()
84.    Dim strEmplName As String
85.    Dim intInquiry As Integer
86.    
87.    strEmplName = txtEmployeeName.Text
88.    intInquiry = MsgBox("Hi, " & strEmplName & Chr(13) & _
89.        "I think we met already." & vbCrLf & _
90.        "I don't know when. I don't know where." & vbCrLf & _
91.        "I don't know why. But I bet we met somewhere.", _
92.        vbYesNo + vbInformation, _
93.        "Meeting Acquaintances")
End Sub
  1. To test the form, press F5.
  2. On the Employee Name text box, type Walter Bennett
  3. Click the Message 8 button and see the result
  4. Click one of the buttons to close the message box
  5. Close the running form, click its close button Close

 

 

The Input Box

 

 

Like a message box, an input box is a (relatively) small form (in reality, it is a dialog box) that displays a message to the user. Unlike a message box, an input box presents a small text box that expects the user to enter a value. After using it, the user can either send the form with the new value or dismiss it without any change.

To create an input box, you can use the InputBox function procedure prompts the user to enter some information in a message box, and the function will return the content of that box.

 

The Character To ASCII Conversion

 

 

The Chr function is used to associate an entered character with its ASCII character equivalent. It could be used to convert a number to a character. It could also be used to break a line in a long expression. The syntax of the Chr function is:

Chr(Number)

A combination of Chr(13) and Chr(10) would break a line in an expression.

 

 

Case Conversion

 

 

If you are presented with a string or an expression whose cases must be the same, you can convert all of its characters in either uppercase or lowercase.

To convert a character, a string or an expression to uppercase, you can call the UCase or the UCase$ function. These functions take one argument as the string or expression to be considered. The syntaxes are:

Function UCase(Letter As Char) As Char
Function UCase(Expression As String) As String

The first version receives one character as argument. If the character is already in uppercase, it would be return the same. If the character is not a readable character, no conversion would happen and the function would return it. If the character is in lowercase, it would be converted to uppercase and the function would then return the uppercase equivalent.

The second version considers the argument supplied as a string. Any letter that is in lowercase in the string would be converted to uppercase. Any letter that is in uppercase would be preserved and would not be changed. Any non-alphabetic character in the string would be kept "as is".

 

Logical Functions

 

 

Is it Empty?

 

 

A logical function is one that checks whether an expression is true or false and then return a Boolean value.

The IsEmpty function check whether a field is empty. Its syntax is:

IsEmpty(Expression)

In this case, the Expression argument will be checked. If it is empty, the IsEmpty function returns True. If the expression or field is not empty, that is, if it contains something, the function returns False.

 

 

Is it Null?

 

 

Another problem you may encounter when involving an operation or the contents of a control is whether it has never contained a value. This operation is sometimes confused with that of checking whether a field is empty. Here is the difference (it is important to understand this because it is used in many other environments):

  • Imagine a text box control is used for first name and the field displays Paul. If the user comes to that record, the field is not empty, it already contains a name, which is this case is Paul. If the user clicks in the field and deletes Paul, the field becomes empty. It is not null
  • Imagine a field is used for first name. If the user comes to a new record, the field for the first name may be empty (if you did not give it a default value). In this case, the field is Null: it is not empty because it has never contained anything. If the user types a name, and then deletes it, the field is not considered Null anymore: it has become empty

To check whether an expression or the value of a control is null, you can call the IsNull() function. Its syntax is:

IsNull(Expression)

Also used on fields, the IsNull() function checks the state of a field (remember, this functions does not check whether a field is empty or not; it checks if the field has ever contained a value). If the field it null, this function returns True. If the field is not null, this function returns False.

 

 

Date and Time Functions

 

 

Current Data and Time

 

 

Microsoft Visual Basic provides various functions to perform date and time related operations. These functions allow you to add dates or times, find the difference between dates or times, or add constant values to dates or times.

The current date is represented by a function called Date. The Date() function is used to get the system date of the computer. You can use it to display today's date, provided your computer has the correct date.

The current time of the computer is represented by a function called Time. The Time() function is used to get the system time of the computer.

The Date() and Time() functions can be combined and are represented by a function called Now.

 

Practical Learning: Using Date and Time

 

 

1.      On the main menu of Microsoft Visual Basic, click View -> Immediate Window.

2.      In the Immediate window, type ?Date and press Enter

3.      Notice that the system date is displayed.

4.      Still in the Immediate window, type ?Time and press Enter

5.      Again, in the Immediate window, type ?Now and press Enter

 

Day - Month - Year

 

 

The Day function is used to get the numeric value that represents a day in the month. It ranges from 1 to 31 included.

The formula of the Day function is Day(DateValue)

The Month function displays the numeric month of a date. It ranges from 1 to 12 included.

The formula of the Month function is Month(DateValue)

The Year function returns the numerical year of a date.

The formula is the Year function is Year(DateValue)

 

Practical Learning: Using Day, Month, and Year Values

 

 

  1. In the Immediate window, type ?Day(#12/14/00#) and press Enter
  2. Notice that the result is 14 as the numeral day of that date
  3. Still in the Immediate window, type ?Day(Date()) and press Enter
  4. Notice that the result is the numeric day of the system date
  5. In the Immediate window, type ?Day(Date()+2) and press Enter
    This would display the numeral of 2 days from today
  6. In the Immediate window, type ?Month("June 12, 1990") and press Enter
  7. Notice that the result in 6, because June represents the 6th month of the year
  8. In the Immediate window, type ?Month("Tuesday, October 02, 1990") and Press Enter.
    This would result in 10.
  9. In the Immediate window, type ?Month(#02/25/90#) and press Enter
    This produces 2 since February is the 2nd day of the year.
  10. In the Immediate window, type ?Year(Date()) and press Enter.
  11. Notice that this displays the current year of the system date

 

 

Adding a Date

 

 

 

The DateAdd function is used to add a date value to another date. It can be used to add a number of days, weeks, months, or years to another date. The formula for the DateAdd function is

DateAdd(Interval, Number, date)

Required, the Interval argument specifies the kind of value you want as a result. This argument will be enclosed between double quotes and can have one of the following values:

Interval

Used To Get

s

Second

n

Minute

h

Hour

w

Numeric Weekday

ww

Week of the Year

d

Day

y

Numeric Day of the Year

m

Month

q

Quarter

yyyy

Year

Required also, the Number argument specifies the number of units you want to add. If you set it as positive, its value will be added. On the other hand, if you want to subtract, make it negative.

The number represents the units of the Interval argument you want to add.

The date argument is the date to which you want to add the number.

 

Subtracting a Date

 

 

The DateDiff function is used to find the difference between two date or time values. It allows you to find the number of seconds, minutes, hours, days, weeks, months, or years from two valid date or time values. The DateDiff function takes 5 arguments, 3 are required and 2 are optional.

The formula of the function is

DateDiff(Interval, Date1, Date2, Option1, Option2)

Required, the Interval argument specifies what kind of value you want as a result. This argument will be enclosed between double quotes and can have one of the following values:

Interval

Used To Get

s

Second

n

Minute

h

Hour

w

Numeric Weekday

ww

Week of the Year

d

Day

y

Numeric Day of the Year

m

Month

q

Quarter

yyyy

Year

Required also, the Date1 and Date2 argument specify the date or time values that will be used when performing the operation.

By default, the days of a week are counted starting on Sunday. If you want to start counting those days on another day, supply the Option1 argument using one of the following values: vbSunday, vbMonday, vbTuesday, vbWednesday, vbThursday, vbFriday, vbSaturday. There are other variances to that argument.

If your calculation involves weeks or finding the number of weeks, by default, the weeks are counted starting January 1st. If you want to count your weeks starting at a different date, use the Option2 argument to specify where the program should start.

 

Practical Learning: Subtracting Dates

 

 

  1. In the Immediate window, type ? DateDiff("d", #12/12/2000#, Now()) and press Enter
  2. Notice this displays the number of days that have since the stated date and today

 

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 Parent’s 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 control’s Left property. The distance from the top border of the parent window to the top border of the control is the control’s 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 computer’s applications. This area is also used to host other objects. Although an object’s 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:

A partial window on the desktop

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 Close

 

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

Description

0 - Manual

Allows you to specify the position of the form using the rectangle in the Form Layout window 

1 - CenterOwner

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

2 - CenterScreen

This form will be centered with regards to the desktop

3 - Windows Default

The application will let the operating system specify the position of the form

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
  1. To test the form, press F5
  2. 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.
  3. After viewing the form, to close it, click its Close button
  4. Notice that the form is back to the dimensions set in the Properties event.
  5. To use another event, on the Project window, click the View Code button
  6. 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:
     
     
  7. Write the code of the DblClick event as follows:
31.Private Sub Form_DblClick()
32.    Me.Caption = "You double-clicked Me!"
End Sub
  1. To test the form, on the main menu, click Run -> Start.
  2. After viewing the form, to close it, on the main menu, click Run -> End.
  3. To add another form to the project, on the Standard toolbar, click the Add Form button
     
  4. From the Add Form dialog box, make sure the Form icon is selected and make sure the check box is not checked.
    Click Open.
  5. As the new form is displaying, in the Properties window, click (Name) and type frmEmployees
  6. Double-click BorderStyle a few times (it should take only one double-click) until it displays 3 - Fixed Dialog
  7. Click Caption and type Employees Records
  8. 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
     
     
  9. 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
  1. To save the project, on the main menu, click File -> Save Project.
  2. To test the project, on the Standard toolbar, click the Start button
  3. To display the other form, double-click in the displayed form.
  4. Notice that the other form displays.
  5. To close the form, click the End button
  6. On the main menu, click Window -> Project1 - frmControls (Form).
  7. In the Properties window, click Height and type 4000
  8. 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)

lblMainTitle

Height

495

Alignment

2 - Center

Left

120

Caption

College Park Auto Parts

Top

120

Font

Times New Roman, Bold, 16

 

4335

  1. On the Toolbox, double-click Frame
  2. On the Properties window, make the following changes:
     

(Name)

fraMake

Top

720

Caption

Make

Visible

True

Height

1575

Width

2055

Left

120

 

 

  1. To test the form, press F5

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

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)

cmdEmployees

Left

120

Caption

Employees

Top

3120

Height

375

Width

1215

  1. To test the form, press F5 (of course, the button doesn't do much because we didn't ask it to do anything).
  2. 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.
  3. 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
  1. To test the effect of the new code, on the Standard toolbar, click the Start button
  2. When the main form is loaded, click the Employees button. Notice that the second displays.
  3. To close the Employees Records form, click its Close button
  4. Notice that the caption did not change on the main form, although it would change if you had double-clicked inside of the form.
  5. To close the main form, click its Close button .
  6. On the Toolbox, double-click CommandButton.
  7. On the Properties window, make the following changes:
     

(Name)

cmdExit

Left

3480

Caption

Exit

Top

3120

Height

375

Width

1215

  1. 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.
  2. Press Tab and type End so your code appears as follows:
17.Private Sub cmdExit_Click()
18.    End
End Sub
  1. To test the functionality of the form as this time, on the Standard toolbar, click the Start button
  2. Click the Employees button
  3. To close the Employees Records form, click its close button .
  4. To close the main form, click Exit.
  5. 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 to call the Font dialog box.
  9. On the Font dialog box, set the font to Times New Roman, Style = Bold, and Size = 22.
  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)

lblFirstName

lblLastName

lblFullName

lblMessage

Caption

First Name

LastName

Full Name

Empty

Height

255

255

255

255

Left

120

120

120

120

Top

705

1125

1560

2160

Width

855

855

855

3975

  1. To test the form, press F5.
  2. 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)

txtFirstName

txtLastName

txtFullName

Height

285

285

285

Left

1080

1080

1080

Text

Empty

Empty

Empty

Top

705

1125

1560

Width

1815

1815

1815

  1. To test the form, press F5.
  2. 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)

fraFord

Top

720

Caption

Ford

Visible

True

Height

1575

Width

2055

Left

2280

 

 

  1. On the Toolbox, click the CheckBox.
  2. 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.
  3. On the Properties window, change the name of the check box to chkFocus and change its caption to Focus.
  4. From the Toolbox, draw another check box inside of the left frame but under the first check box.
  5. Change the name of the new check box to chkEscort and its caption to Escort
  6. From the Toolbox, draw another check box inside of the left frame but under the second check box.
  7. Change the name of the new check box to chkTaurus and its caption to Taurus
  8. To test the form, press F5
  9. To close the running form, click its close button

 

 

 

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
  1. To test the form, press F5
  2. 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
  1. 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.
  2. 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.
  3. Edit the Click event as follows:
30.Private Sub cmdCountryChoice_Click()
31.    txtCountry.Text = lstCountry.Text
End Sub
  1. Click the Object combo box and select lstCountry. That initializes the events for the list box.
  2. 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
  3. Edit the Double Click procedure as follows
35.Private Sub lstCountry_DblClick()
36.    cmdCountryChoice.Value = True
End Sub
  1. To test the form, on the Standard toolbar, click the Start button
  2. Double-click Costa Rica. Double-click Greece. Notice that the country double-clicked displays in the text box.
  3. 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.
  4. To test the form, press F5
  5. To close the running form, click its close button .

 

ADO Fundamentals

 

 

 

Overview

 

 

Introduction

 

 

Microsoft Windows was created to solve various kinds of computer problems. Text or word processing was taken care of easily as it can be performed using WordPad, an application that ships with every installation of the operating system. All regular calculations were also taken care of as can be verified in Calculator, an application that also ships with MS Window. Basic drawing and graphics can be performed using Paint, another application that is installed with MS Windows.

To support databases in MS Windows, Microsoft created a library called ActiveX Data Objects or ADO. ADO was meant to create, administer, and manipulate databases. To use ADO, you had to first create a database using an application such as Microsoft Access or by other related means. Because this only partly solved the problem, and because this almost restricted people to use Microsoft Access, there was need for additional solutions. Among the limitations of ADO, there was security and even the ability to create a database without necessarily using a product from Microsoft. To address these issues, Microsoft created an additional library called 
Microsoft ActiveX Data Objects Extensions for Data Definition Language and Security, abbreviated ADOX. Nowadays, Microsoft has made free everything you need to create, manage, and even distribute databases (in fact, at this time, except for the operating systems,  Microsoft has developed various libraries and compilers and made them completely free so that you can create any type of application without spending money: you only need time to use them).

 

Using ADO

 

Although treated as one entity, Microsoft ActiveX Data Object is really many libraries grouped under one name. For the rest of our lessons, ADO will be used to refer to all the technologies we need to create and administer our databases. We will point the differences only when needed.

ADO is only a library, that is, a series of files that provide "drivers" and documentation to perform a task. In order to use ADO, you need a programming or development environment in which you can write code. The environment you use should/must also be able to "understand" your code, analyze it and produce a result. This is not an anomaly of ADO. All libraries work like that. There are many environments you can use with ADO. Some of them are Microsoft Internet Explorer (using scripting languages such as VBScript or JavaScript), Borland Delphi, Microsoft Visual C++, Visual InterDev, Borland C++ Builder, Microsoft Visual Studio. NET, just to name a few.

Author Note

When writing the exercises on this site, we had to decide and choose among various available options, unfortunately. Different programming environments offer different advantages and disadvantages. On this site, we will create all of our databases using Microsoft Visual Basic 6. We chose it because at the time of this writing, we found out that many people are still using it. Of course, Microsoft Access would offer the same flexibility but we preferred this because MS Access is already a complete database environment in its own right.

In order to follow the lessons on this site, you are supposed to have some knowledge of Microsoft Visual Basic as it is the main language of ADO. The topics you are:

  • Variables
  • Procedures and Functions
  • Objects and Methods of Objects
  • Conditional Statements

It would be a big waste of time to try to teach both MSVB (which is a language or a programming environment) and ADO (which is a library).

 

 

Object-Oriented ADO

 

 

 

 

 

Connections

 

 

Introduction

 

 

To make database programming more professional and constructive, ADO uses a series of objects. The objects mimic their concept from real life. Consider an object like a house. It has some characteristics like the number of rooms, the color of the roof, the type of house, etc. In the programming world, a characteristic of an object is called a property. A property is a word that describes an object. An object can also carry assignments. For example, one of the assignments of a house is to protect from rain the people who live in it. In the programming world, an assignment carried by an object is called a method.

 

Practical Learning: Introducing ADO

 

 

  1. If you want to follow the lessons on this site, open Windows Explorer and, on the C: drive, create a folder named ADO Lessons

New Folder

  1. Open Microsoft Visual Basic 6 or the programming environment you will use for these lessons (remember that, and for the rest of our lessons, we will use Visual Basic 6)
     
  2. On the opening dialog box, click Standard EXE and click Open
  3. Start saving the project. Create a new folder inside of the ADO Lessons folder and name it Fundamentals:
     
    Save File As
  4. Display the new folder in the Save In combo box
  5. Change the name of the form file to Main and click Save
  6. Save the project as Fundamentals

 

ADOX Fundamentals

 

 

The most fundamental object used in ADO databases is ADOX. To use this object, you must create a reference to it. To do this, first declare a variable of type ADOX. The ADOX object is equipped with the Catalog property. This property defines most of the objects you will need to use in your databases, the objects we will start introducing in the next lesson. To use the Catalog property, specify it when declaring the ADOX variable. Here is an example:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
End Sub

Before using the Catalog property of the ADOX object, you must specify that you need a reference to it, this can be done by initializing your variable with ADOX.Catalog using the New operator. Here is an example:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
End Sub

You can also refer to this property when declaring the variable. Here is an example:

Private Sub cmdAction_Click()
    Dim objCatalog As New ADOX.Catalog
End Sub

Whenever you create an ADO object and while it is being used, it consumes resources. Therefore, after using the object, you should/must remove it from memory (if you don't, you may start seeing abnormal behavior on your computer after a while, as resources become scarce for other objects or applications are trying to use the same resources). To remove a resource from memory, after using it, assign it the Nothing constant.

 

Practical Learning: Getting a Reference to ADO

 

 

  1. If you are using Visual Basic 6, on the main menu, click Project -> References...
  2. In the Available References list check box of the References dialog box, click the check box of Microsoft ADO Ext. 2.7 For DDL And Security
     
    References
  3. Click OK
  4. On the Toolbox, double-click the CommandButton
  5. Change its Caption to Create Database and its Name to cmdCreateDatabase
     
    ADO Fundamentals
  6. Double-click the button
  7. To get a reference to ADOX, declare the following variable and make sure you set it to Nothing before the closing of the procedure:
     
Private Sub cmdCreateDatabase_Click()
    Dim catConnection As ADOX.Catalog
    
    Set catConnection = Nothing
End Sub
  1. Save all

 

Database Creation

 

 

Introduction

 

 

Once you have gotten a reference to the object you want to use, you can perform a related operation. The primary operation you can perform consists of creating a database. This is done using the Catalog property of the ADOX object. To create a database, you can call the Create() method of the Catalog. This would be started as follows:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
    
    objCatalog.Create
End Sub

This method takes as argument a string, also called a connection string, that defines the assignment to perform. The string itself is internally made of different sections separated by a semi-colon.

The first part of the connection string is called the provider. It specifies the platform used to handle the database. To specify this factor, assign the desired name to the provider word. This would be done as:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
    
    objCatalog.Create "provider="
End Sub

Although there are various providers in the industry, there are two primary providers used in ADO. One of them is Microsoft SQL Server and it is represented by SQLOLEDB. Therefore, if your database will reside on a SQL Server, you can specify the provider as follows:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
    
    objCatalog.Create "provider=SQLOEDB"
End Sub

Probably the most used provider in Visual Basic 6 databases is the Microsoft JET database engine. It is represented as Microsoft.JET.OLEDB.4.0. You can use it to specify the provider as follows:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
    
    objCatalog.Create "provide=Microsoft.Jet.OLEDB.4.0"
End Sub

You can also include the name of the provider as its own string. To do that, you can include it in single-quotes:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
    
    objCatalog.Create "provider='Microsoft.Jet.OLEDB.4.0'"
End Sub

If you are creating a SQL Server type of database, there are various other details you must provide to the connection string. For the rest of our lessons, we will use Microsoft JET. When using Microsoft JET, the second part of the connection is referred to as the data source. If you are creating a database, you can specify the path and the name of the database to the Data Source factor. The path must consist of the drive and the folder(s). After the last folder, the name of the database must have the .mdb extension. For example, to create a database called Exercise that would reside in a folder called Exercises in the C: drive, you can specify the connection string as follows:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
    
    objCatalog.Create "provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Exercises\Exercise.mdb"
End Sub

To be safer, you can also include the value of the data source in single-quotes:

Private Sub cmdAction_Click()
    Dim objCatalog As ADOX.Catalog
    
    Set objCatalog = New ADOX.Catalog
    
    objCatalog.Create "provide=Microsoft.Jet.OLEDB.4.0;'Data Source=C:\Exercises\Exercises.mdb'"
End Sub

 

Practical Learning: Creating a Database

 

 

  1. To create a new database, change the event as follows:
     
Private Sub cmdCreateDatabase_Click()
    Dim catConnection As ADOX.Catalog
    
    Set catConnection = New ADOX.Catalog
    catConnection.Create "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                         "Data Source='C:\ADO Lessons\Fundamentals\Fundamentals.mdb'"
    
    MsgBox "A new Microsoft JET database named Fundamentals.mdb has been created"
    
    Set catConnection = Nothing
End Sub
  1. To execute the application, press F5
  2. To create the database, click the Create Database button:
     
  3. Open Windows Explorer and open the folder that contains the current project to check that the database has been created:
     
  4. Return to MSVB

 

 

Tables Fundamentals

 

 

 

 

Overview of Tables

 

 

Introduction

 

 

A database is primarily a list of items, such as names of family members: Judie, Ernest, Bill, David, Hermine. Such a list can be created as follows:

Family Members
 

 

Name

Judie

Ernest

Bill

David

Hermine

To make the list more elaborate, each entry can contain other internal information, such as the age, the gender, the type of relationship, etc. Here is an example:

Family Members
 

 

Name

Age

Gender

Relationship

Judie

18

Female

Sister

Ernest

24

Male

Cousin

Bill

52

Unknown

Uncle

David

36

Male

Brother

Hermine

12

Unknown

Niece

This arrangement makes it easy to visualize the items in the list and to locate data. Information is organized by categories. The categories are vertically positioned. Each category is also called a column. Information is also organized horizontally in each line called a row. The information that belongs to the same row is also called a record.

Practical Learning: Introducing Tables

 

 

  1. If you want to follow the lessons on this site, Start Microsoft Visual Basic 6 or the programming environment you will use for these lessons
     
  2. On the opening dialog box, click Standard EXE and click Open
  3. Save the project in a new folder inside of your ADO Lessons folder and name it MVA1
  4. Save the file of the form as Main and save the project as MVA
  5. Add a new command button to the form. Change its Caption to Create Database and its Name to cmdCreateDatabase
  6. Use the same approach of our previous lesson to create a new database named MVA and store it in the above Tables folder (don't forget to add a reference to ADOX using the References dialog box):
     
Option Explicit
 
Private Sub cmdCreateDatabase_Click()
    Dim conCatalog As ADOX.Catalog
    
    Set conCatalog = New ADOX.Catalog
    conCatalog.Create "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                      "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    MsgBox "A new Microsoft JET database named MVA.mdb has been created"
    
    Set conCatalog = Nothing
End Sub
  1. Execute the application and execute the statement
  2. To allow the user to create other databases, change the design of the form as follows (the name of the text box displays in it):
     
  3. Change the code of the Click event of the button as follows:
     
Private Sub cmdCreateDatabase_Click()
    Dim conCatalog As ADOX.Catalog
    Dim strDbName As String
    
    Set conCatalog = New ADOX.Catalog
    strDbName = "C:\ADO Lessons\" & Me.txtDatabaseName.Text & ".mdb"
    conCatalog.Create "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                      "Data Source=" & strDbName
    
MsgBox "A new Microsoft JET database named " & strDbName & " has been created"
    
    Set conCatalog = Nothing
End Sub
  1. Save All

 

Table Creation

 

 

To create a table, you start a statement with the CREATE TABLE expression followed by the desired name of the table as follows:

CREATE TABLE TableName

When creating a table, you must provide a name for it. The name of a table can be made of digits, letters, underscores, or a combination of those. In our lessons, we will use the following rules:

  • The name will start with a letter in uppercase. Examples are Employees, Members
  • After the first letter, the name can have letters, digits, underscores or a combination of those. Examples are Title_1, Category_A_2
  • If the name is a combination of words, each part will start with an uppercase letter. Examples are FullNames, StatesAndCapitals
  • We will use one word names; that is, no space in the name

Every table must have at least one column. The list of columns of a table starts with an opening parenthesis “(“ and ends with a closing parenthesis “)”. If the table will be made of more than one column, you can separate them with a comma. The syntax used would be:

CREATE TABLE TableName(Column1, Column2, Column_n);

To create a column, you specify its name, followed by its data type, and some possible options. Therefore, the syntax of creating a column is:

ColumnName DataType Options

Notice that there is only space that separates the sections of the syntax. For this reason, the name of a column should be in one word because, if you put space after the first word, the SQL engine would treat the next word as a data type. For example, the following statement would produce an error:

CREATE TABLE Test(Marital Status)

If you want to use space in a column name, include it between an opening square bracket “[“ and a closing square bracket “]”. The above statement would be changed to:

CREATE TABLE Test([Marital Status])

After (or on the right side of) the column name, you must specify the type of information, also called the data type) that will be stored in the cells under that column. Here are the data types you can use:

Data Type

Description

Char or Text

The char or the text data types can be used for columns whose fields would receive (or present) text. The field must not contain more than 255 characters

Varchar

This is one of the most regularly used data types of a SQL column. It can used for strings (text) of any kind

Memo

The cell of a Memo type can hold text of up to 65656 characters

Bit

This is used for a Boolean or logical field that accept only a True or False, a Yes or No, an On or Off, or a 0 or –1 as a value

Smallint

The smallint data type can be used for a field that would hold numbers that can range from –32,768 to 32767

Int or Integer

Each of these data types can be used to represent a natural number 

Long

This is used for fields that would hold small to very large natural numbers

Real

Real is a relatively small data type in the world of double-precision representation but can be used on a column whose fields would hold numbers that can range from – 3.402823E38 to – 1.401298E-45 for negative values or from 1.401298E-45 to 3.402823E38 for positive values

Float

The float data type can be used on a column whose fields would hold numbers with a decimal portion. Like the Single data type, the float is mainly on a column where number precision is not a significant issue

Numeric

The numeric data type can be used on a column whose fields would hold numbers with a decimal portion

Double

The Double data type is the preferred data type for cells that would hold decimal numbers

Money and Currency

This data type is appropriate for fields that would hold numbers that represent monetary values

DateTime

The DATETIME data type can be applied to a column whose fields would display either date, time or both date and time values

 
Here is an example that creates a table and names it Persons

CREATE TABLE Persons
(
FirstName VARCHAR,
[Last Name] varchar,
Gender int,
[Date Of Birth] DateTime,
MaritalStatus Integer,
IsMarried Bit,
PersonalIncome Money,
HouseholdIncome Currency
);

A field size can be used to specify the size of value used on a field. Based on this, when creating a column whose data type is char, text or varchar, you can optionally specify the desired number of characters that the field should allow. To specify the maximum number of characters of a text-based field, include it in parentheses just to the left of the data type.

In ADO, to create a table, you include its whole statement between double-quotes, as a string. To actually perform the assignment, you can call the Execute() method of the ADO reference you are using, passing your string as argument.

 

Practical Learning: Creating a Table

 

 

  1. Add a new command button to the form
  2. Change its Caption to Create Table and name it cmdCreateTable
  3. Generate its Click event and implement it as follows:
     
Private Sub cmdCreateTable_Click()
    Dim conEmployees As ADODB.Connection
    Dim strSQL As String
    
    Set conEmployees = New ADODB.Connection
    conEmployees.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                      "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    strSQL = "CREATE TABLE Employees (" & _
             "DateHired DateTime," & _
             "EmplNumber Text(6)," & _
             "Dept int," & _
             "FirstName VarChar(20)," & _
             "LastName varchar(20)," & _
             "Address varchar(50)," & _
             "City VARCHAR(40)," & _
             "State VarChar(32));"
    
    conEmployees.Execute strSQL
    
    MsgBox "A table named Employees has been added to the MVA.mdb database"
    
    Set conEmployees = Nothing
End Sub
  1. To add a reference to ADO, on the main menu, click Project -> References...
  2. In the Available References checked list box of the References dialog box, click the check box of your latest ADO driver:
     
    References
  3. Click OK
  4. Test the application and execute the new statement by clicking the second button
     
    Motor Vehicle Administration
  5. Return to your programming environment
  6. To create another table, change the code of the Create Table button as follows:
     
Private Sub cmdCreateTable_Click()
    Dim conTable As ADODB.Connection
    Dim strSQL As String
    
    Set conTable = New ADODB.Connection
    conTable.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                  "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    strSQL = "CREATE TABLE Departments(DeptName VarChar(40), Description varchar(255));"
    
    conTable.Execute strSQL
    
    MsgBox "A table named Departments has been added to the MVA.mdb database"
     
    Set conTable = Nothing
End Sub
  1. Test the application and execute the statement of the button
  2. Return to your programming environment

 

Table Deletion

 

 

If you have a table in a database but don't need that table anymore, you can get rid of it. To delete a table, write the DROP TABLE expression followed by the name of the table.

 

Practical Learning: Deleting a Table

 

 

  1. Add a new command button to the form
  2. Change its Caption to Delete Table and its Name to cmdDeleteTable
  3. Double-click the Delete Table button and implement its Click event as follows:
     
Private Sub cmdDeleteTable_Click()
    Dim conDepartments As ADODB.Connection
    Dim strSQL As String
    
    Set conDepartments = New ADODB.Connection
    conDepartments.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                        "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    strSQL = "DROP TABLE Departments;"
    
    conDepartments.Execute strSQL
    
    MsgBox "The Departments table of the MVA.mdb database has been deleted"
    
    Set conDepartments = Nothing
End Sub
  1. Execute the application and click the Delete Table button
     
  2. Return to your programming environment

 

Columns Management

 

 

Introduction

 

 

After creating a table, you may not like its structure. Instead of deleting it to recreate it, you can simply modify it. To make any modification on a table, you can start with the ALTER TABLE expression followed by the name of the table.
 

 

Column Addition

 

 

One of the operations you can perform to manage a table consists of adding a new column to a table. This is done with the ADD operator followed by the name of the new column and some options, if any.

 

Practical Learning: Adding a New Column to a Table

 

 

  1. This lesson continues from the previous lesson
    Add a new command button to the form
  2. Change its Caption to Modify Table and its Name to cmdModifyTable
  3. Double-click the new button and implement its Click event as follows:
     
Private Sub cmdModifyTable_Click()
    Dim conModify As ADODB.Connection
    Dim strSQL As String
    
    Set conModify = New ADODB.Connection
    conModify.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                   "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    strSQL = "ALTER TABLE Employees Add EmployeeReviews Memo;"
    
    conModify.Execute strSQL
    
    MsgBox "A new column named EmployeeReviews has been added to " & _
           "the Employees table of the MVA.mdb database has been deleted"
    
    Set conModify = Nothing
End Sub
  1. Test the application and the button
     
  2. Return to your programming environment

 

Column Deletion

 

 

As opposed to creating a new column, if you have a column that has become useless on a table, you can get rid of it. To delete a column, use the DROP COLUMN expression followed by the name of the column. Before deleting a column, make sure it exists on the table.

Here is an example:

Private Sub cmdAlterTable_Click()
    Dim conEmployees As ADODB.Connection
    Dim strSQL As String
    
    Set conEmployees = New ADODB.Connection
    conEmployees.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                      "Data Source='C:\Programs\MSVB\ADO2\MVA1.mdb'"
    
    strSQL = "ALTER TABLE Employees DROP COLUMN Notes;"
    
    conEmployees.Execute strSQL
    
    MsgBox "The Notes column of the Employees table has been removed"
    
    Set conEmployees = Nothing
End Sub

 

Practical Learning: Deleting a Column

 

 

  1. Change the code of the Modify Table button as follows:
     
Private Sub cmdModifyTable_Click()
    Dim conModify As ADODB.Connection
    Dim strSQL As String
    
    Set conModify = New ADODB.Connection
    conModify.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                   "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    strSQL = "ALTER TABLE Employees DROP COLUMN Dept;"
    
    conModify.Execute strSQL
    
    MsgBox "The Dept column of the Employees table has been removed"
    
    Set conModify = Nothing
End Sub
  1. Test the application and the button
     
  2. Return to your programming environment
  3. To add a new column to the table, change the code of the Modify button as follows:
     
Private Sub cmdModifyTable_Click()
    Dim conModify As ADODB.Connection
    Dim strSQL As String
    
    Set conModify = New ADODB.Connection
    conModify.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                   "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    strSQL = "ALTER TABLE Employees ADD Department Double;"
    
    conModify.Execute strSQL
    
    MsgBox "A Department column that can handle decimal values " & vbCrLf & _
           "has been added to the Employees table"
    
    Set conModify = Nothing
End Sub
  1. Execute the application and the the new statement
     
  2. Return to your programming environment

 

Column Modification

 

 

If a certain aspect of a column is wrong while its name fine, you can modify the column without deleting and recreating it. To modify an aspect of the column, use the ALTER COLUMN, followed by the name of the column, and the modification to perform. For example, to change the data type and optionally the length of data, on the right side of the column name, enter the data type and the option.

 

Practical Learning: Modifying a Column

 

 

  1. Change the code of the Modify Table button as follows:
     
Private Sub cmdModifyTable_Click()
    Dim conModify As ADODB.Connection
    Dim strSQL As String
    
    Set conModify = New ADODB.Connection
    conModify.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                   "Data Source='C:\ADO Lessons\MVA1\MVA.mdb'"
    
    strSQL = "ALTER TABLE Employees ALTER COLUMN Department VarChar(40);"
    
    conModify.Execute strSQL
    
    MsgBox "The data type of the Employees column of the Employees table" & _
           vbCrLf & _
           "has been modified to handle text"
    
    Set conModify = Nothing
End Sub
  1. Test the application and the button
     
    MVA - Modifying a column
  2. Return to your programming environment

 

The ADO Set of Records

 

 

A Set of Records

 

Creating a table provides you with a structure in which you can create a list of values. When a table has been created, it is initially empty but an empty placeholder is automatically created for each column:

Family Members
 

 

Name

Age

Gender

Relationship

 

 

 

 

Therefore, after creating a table, you can populate it. Since an empty placeholder is created under each column, you can start by adding one value for each category. When a value has been created for each column, even if you skip some columns, you are said to have created a record. Here is an example:

 

Family Members
 

 

Name

Age

Gender

Relationship

Judie

18

Female

Sister

 

 

 

 

In the same way, you can keep adding records as you see fit. Every time you have created a record, a placeholder for a new record is automatically made available so you don't have to wonder when a record would go. This also implies that each new record you create is appended, that is, it is added to the end, of the table. Here is an example of a table with records:

Family Members
 

 

Name

Age

Gender

Relationship

Judie

18

Female

Sister

Ernest

24

Male

 

Bill

52

 

Uncle

David

36

Male

Brother

Hermine

 

Unknown

Niece

 

Practical LearningPractical Learning: Introducing Record Sets

 

  1. If you want to follow this lessons, Start Microsoft Visual Basic 6 or your programming environment
     
  2. On the opening dialog box, click Standard EXE and click Open
  3. Save the project in a new folder inside of your ADO Lessons folder and name it MVA2
  4. Save the file of the form as Main and save the project as Motor Vehicle Administration1
     
  5. Double-click an empty area of the form to access its Load event
  6. Use the same approach as done previously to create a new database named MVA and store it in the above Tables folder (don't forget to add a reference to ADOX using the References dialog box):
     
Private Sub Form_Load()
    Dim conCatalog As ADOX.Catalog
    
    Set conCatalog = New ADOX.Catalog
    conCatalog.Create "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                      "Data Source='C:\ADO Lessons\MVA2\MVA.mdb'"
    
    MsgBox "A new Microsoft JET database named MVA.mdb has been created"
    
    Set conCatalog = Nothing
End Sub
  1. Execute the application
     
  2. Click the OK button then close the form
  3. To create a new table, change the code of the Load event event as follows:
     
Private Sub Form_Load()
    Dim conEmployees As ADODB.Connection
    
    Set conEmployees = New ADODB.Connection
    conEmployees.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                      "Data Source='C:\ADO Lessons\MVA2\MVA.mdb'"
    
    conEmployees.Execute "CREATE TABLE Employees(" & _
                         "EmplNumber Text(6)," & _
                         "DateHired DateTime," & _
                         "FirstName VarChar(20)," & _
                         "LastName varchar(20)," & _
                         "Department varchar(40)," & _
                         "EmailAddress varchar(50));"
    
    MsgBox "A table named Employees has been added to the MVA.mdb database"
    
    Set conEmployees = Nothing
End Sub
  1. Add a reference to your most recent ADO driver using the References dialog box
  2. Execute the application
     
  3. Click OK then close the form
  4. Delete the whole code of the Load event

 

The Recordset Object

 

 

The group of records that belong to a table is called a set of records. In ADO, whenever you need to deal with the set of records of a table, you should first declare a variable that would hold the records. To do this, you must obtain an appropriate reference to ADODB. A set of records of a table in ADO is managed by an object called Recordset.

After obtaining a reference to a Recordset object, in order to use it, you must open it. This is done using its Open() method whose syntax is:

recordset.Open Source, ActiveConnection, CursorType, LockType, Options

The first argument to this method can be a different thing depending on the circumstance. For example, if you are trying to deal with the records of a table, this argument can be the name of that table.

The second argument specifies how the connection will be carried. It can be the name of a Connection reference you previously established. The rest of the arguments are optional. In other words, if you don't specify their values, they would use a default.

The third argument specifies the type of cursor that would be used. The available options are stored in an enumerator called CursorTypeEnum and they are:  

 

Constant

Value

Description

adOpenUnspecified

-1

Does not specify the type of cursor

adOpenForwardOnly

0

Uses a forward-only cursor
Identical to a static cursor, except that you can only scroll forward through records. This improves performance when you need to make only one pass through a Recordset

adOpenKeyset

1

Uses a keyset cursor
Like a dynamic cursor, except that you can't see records that other users add, although records that other users delete are inaccessible from your Recordset. Data changes by other users are still visible

adOpenDynamic

2

Uses a dynamic cursor
Additions, changes, and deletions by other users are visible, and all types of movement through the Recordset are allowed, except for bookmarks, if the provider doesn't support them

adOpenStatic

3

Uses a static cursor, which is a static copy of a set of records that you can use to find data or generate reports. Additions, changes, or deletions by other users are not visible

 

The default value of this argument is adOpenForwardOnly.

The fourth argument specifies the type of locking system that would be used on the set of records. The available options are stored in an enumerator called LockTypeEnum and they are:

 

Constant

Value

Description

adLockUnspecified

-1

Does not specify a type of lock. For clones, the clone is created with the same lock type as the original

adLockReadOnly

1

Indicates read-only records. You cannot alter the data

adLockPessimistic

2

Indicates pessimistic locking, record by record. The provider does what is necessary to ensure successful editing of the records, usually by locking records at the data source immediately after editing

adLockOptimistic

3

Indicates optimistic locking, record by record. The provider uses optimistic locking, locking records only when you call the Update method

adLockBatchOptimistic

4

Indicates optimistic batch updates. Required for batch update mode

 

The last argument is an option you specify about the first argument.

 

Record Creation

 

 

One of the actions you can perform using a Recordset object is to perform data entry, that is, to create new records. To support data entry, the Recordset object is equipped with the AddNew() method. Its syntax is:

recordset.AddNew FieldList, Values

The first argument is a name of a column and must be identified as belonging to an array called Fields. After specifying the name of the column in the parentheses of the Fields array, you can assign it the desired value. You can do this for each column or for selected columns of the table.

After creating a record, you should remember to save it. This is done by calling the Update() method of the Recordset object.

 

 

Practical LearningPractical Learning: Performing Data Entry

 

 

  1. Design the form as follows (the names of the text boxes are displayed in them; the left command button is named cmdSubmitRecord):
     
    Motor Vehicle Administration
  2. Double-click the Submit Record button and implement its Click event as follows:
     
Private Sub cmdSubmitRecord_Click()
    Dim rcsEmployees As New ADODB.Recordset
    Dim conEmployees As New ADODB.Connection
    
    conEmployees.Open "Provider='Microsoft.JET.OLEDB.4.0';" & _
                      "Data Source='C:\ADO Lessons\MVA2\MVA.mdb'"
    rcsEmployees.Open "Employees", conEmployees, adOpenStatic, adLockOptimistic
    
    If rcsEmployees.Supports(adAddNew) Then
        With rcsEmployees
            .AddNew
            .Fields("EmplNumber") = Me.txtEmployeeNbr.Text
            .Fields("DateHired") = Me.txtDateHired.Text
            .Fields("FirstName") = Me.txtFirstName.Text
            .Fields("LastName") = Me.txtLastName.Text
            .Fields("Department") = Me.txtDepartment.Text
            .Fields("EmailAddress") = Me.txtEmailAddress.Text
            .Update
        End With
        
        MsgBox "A new record has been added to the Employees table"
    End If
    
    Me.txtEmployeeNbr.Text = ""
    Me.txtDateHired.Text = ""
    Me.txtFirstName.Text = ""
    Me.txtLastName.Text = ""
    Me.txtDepartment.Text = ""
    Me.txtEmailAddress.Text = ""
    Me.txtEmployeeNbr.SetFocus
 
    rcsEmployees.Close
    Set rcsEmployees = Nothing
    conEmployees.Close
    Set rcsEmployees = Nothing
End Sub
  1. Execute the application and create a new record:
     

  1. After creating a new record, click the Submit Record button:
     

  1. In the same way, create a few more records

 

 

 

Record Insertion

 

 

Besides, or as opposed to, adding a new record, if you don't want to formally use the Recordset class to create a record, you can use the Execute() method of the Connection object. To create a new record using the Connection object, you can call the Execute() method and pass it a string that contains the following formula:

INSERT TableName VALUES(Name1, Name2, Name_n)

or

INSERT INTO TableName VALUES(Name1, Name2, Name_n)

 

 

Practical LearningPractical Learning: Inserting a new Record

 

 

  1. Add a new command button to the right of the first
  2. Change its Caption to Insert Record and its Name to cmdInsertRecord
  3. Double-click the button and implement its Click event as follows:
     
Private Sub cmdInsertRecord_Click()
    Dim conEmployees As New ADODB.Connection
    Dim strSQL As String
    
    conEmployees.Open "Provider='Microsoft.JET.OLEDB.4.0';" & _
                      "Data Source='C:\ADO Lessons\MVA2\MVA.mdb'"
    
    strSQL = "INSERT INTO Employees VALUES ('" & _
             txtEmployeeNbr.Text & "', '" & _
             txtDateHired.Text & "', '" & _
             txtFirstName.Text & "', '" & _
             txtLastName.Text & "', '" & _
             txtDepartment.Text & "', '" & _
             txtEmailAddress.Text & "')"
    
    conEmployees.Execute strSQL
    MsgBox "The Employees table has been updated with a new record"
    
    Me.txtEmployeeNbr.Text = ""
    Me.txtDateHired.Text = ""
    Me.txtFirstName.Text = ""
    Me.txtLastName.Text = ""
    Me.txtDepartment.Text = ""
    Me.txtEmailAddress.Text = ""
    Me.txtEmployeeNbr.SetFocus
 
    conEmployees.Close
    Set conEmployees = Nothing
End Sub
  1. Execute the application and enter a new value in each text box then click Insert Record
     
  2. Return to your programming environment

 

Data Navigation

 

 

 

 

 

Introduction

 

 

To make information of a table available to the user, you can display it on a form, a web page, etc. There are two main types of display used for the records. You can display all records in a type of table or grid made of columns and rows, as done on a spreadsheet like StarCalc, Microsoft Excel, or Corel Quattro Pro, etc. You can also display only one record. Whatever technique you use, you should provide the user with the means of moving from one record to another. While this is usually easy on a spreadsheet that displays as many records as can be seen, if you decide to display one record at a time, you can then create some buttons that the user would click to navigate through records.
 

 

Practical Learning: Navigating Through Records

 

 

  1. This exercise continues from the previous lesson
    Add a new form to the project
  2. Copy the labels and text boxes on the first form and paste them in the second form
  3. Add five new command buttons and a label to the form designed as follows:
     

The new controls are named from left to right as cmdClose, cmdFirst, cmdPrevious, lblRecNbr, cmdNext, cmdLast

  1. Save the form's file as EmplRecords
  2. Double-click and empty area of the form to access its Load event then return to the form
  3. Double-click all buttons
  4. Implement the module as follows:
     
Option Explicit
Dim conEmployees As New ADODB.Connection
Dim rcsEmployees As New ADODB.Recordset
Dim intRecNumber As Integer
 
Private Sub cmdClose_Click()
    Hide
End Sub
 
Private Sub cmdFirst_Click()
    rcsEmployees.MoveFirst
    intRecNumber = 0
                     
    Me.txtEmployeeNbr.Text = rcsEmployees.Fields("EmplNumber")
    Me.txtDateHired.Text = rcsEmployees.Fields("DateHired")
    Me.txtFirstName.Text = rcsEmployees.Fields("FirstName")
    Me.txtLastName.Text = rcsEmployees.Fields("LastName")
    Me.txtDepartment.Text = rcsEmployees.Fields("Department")
    Me.txtEmailAddress.Text = rcsEmployees.Fields("EmailAddress")
        
    Me.lblRecNbr.Caption = "1 of " & rcsEmployees.RecordCount
End Sub
 
Private Sub cmdLast_Click()
    rcsEmployees.MoveLast
    intRecNumber = rcsEmployees.RecordCount
    
    Me.txtEmployeeNbr.Text = rcsEmployees.Fields("EmplNumber")
    Me.txtDateHired.Text = rcsEmployees.Fields("DateHired")
    Me.txtFirstName.Text = rcsEmployees.Fields("FirstName")
    Me.txtLastName.Text = rcsEmployees.Fields("LastName")
    Me.txtDepartment.Text = rcsEmployees.Fields("Department")
    Me.txtEmailAddress.Text = rcsEmployees.Fields("EmailAddress")
        
    Me.lblRecNbr.Caption = CStr(intRecNumber) & " of " & _
                               rcsEmployees.RecordCount
End Sub
 
Private Sub cmdNext_Click()
    rcsEmployees.MoveNext
    intRecNumber = intRecNumber + 1
    
    If Not rcsEmployees.EOF Then
        Me.txtEmployeeNbr.Text = rcsEmployees.Fields("EmplNumber")
        Me.txtDateHired.Text = rcsEmployees.Fields("DateHired")
        Me.txtFirstName.Text = rcsEmployees.Fields("FirstName")
        Me.txtLastName.Text = rcsEmployees.Fields("LastName")
        Me.txtDepartment.Text = rcsEmployees.Fields("Department")
        Me.txtEmailAddress.Text = rcsEmployees.Fields("EmailAddress")
            
        Me.lblRecNbr.Caption = CStr(intRecNumber + 1) & " of _
                               " & rcsEmployees.RecordCount
    Else
        cmdLast_Click
    End If
End Sub
 
Private Sub cmdPrevious_Click()
    rcsEmployees.MovePrevious
    intRecNumber = intRecNumber - 1
    
    If Not rcsEmployees.BOF Then
        Me.txtEmployeeNbr.Text = rcsEmployees.Fields("EmplNumber")
        Me.txtDateHired.Text = rcsEmployees.Fields("DateHired")
        Me.txtFirstName.Text = rcsEmployees.Fields("FirstName")
        Me.txtLastName.Text = rcsEmployees.Fields("LastName")
        Me.txtDepartment.Text = rcsEmployees.Fields("Department")
        Me.txtEmailAddress.Text = rcsEmployees.Fields("EmailAddress")
            
        Me.lblRecNbr.Caption = CStr(intRecNumber) & " of " & _
                               rcsEmployees.RecordCount
    Else
        cmdFirst_Click
    End If
End Sub
 
Private Sub Form_Load()
    intRecNumber = 0
    
    conEmployees.Open "Provider='Microsoft.JET.OLEDB.4.0';" & _
                      "Data Source='C:\ADO Lessons\MVA2\MVA.mdb'"
    rcsEmployees.Open "Employees", conEmployees, _
                       adOpenStatic, adLockOptimistic
    
    Me.txtEmployeeNbr.Text = rcsEmployees.Fields("EmplNumber")
    Me.txtDateHired.Text = rcsEmployees.Fields("DateHired")
    Me.txtFirstName.Text = rcsEmployees.Fields("FirstName")
    Me.txtLastName.Text = rcsEmployees.Fields("LastName")
    Me.txtDepartment.Text = rcsEmployees.Fields("Department")
    Me.txtEmailAddress.Text = rcsEmployees.Fields("EmailAddress")
    
    Me.lblRecNbr.Caption = CStr(intRecNumber + 1) & " of " & _
                               rcsEmployees.RecordCount
End Sub
 
Private Sub Form_Unload(Cancel As Integer)
    rcsEmployees.Close
    conEmployees.Close
    Set rcsEmployees = Nothing
    Set conEmployees = Nothing
End Sub
  1. Add two number buttons to the firs form as follows:
     

The new buttons are named cmdEmplRecords and cmdClose

  1. Double-click the new buttons and implement their Click events as follows:
     
Private Sub cmdClose_Click()
    End
End Sub
 
Private Sub cmdEmplRecords_Click()
    Form2.Show
End Sub
  1. Execute the application
  2. Return to your programming environment

 

U can Download From http://rapidshare.com/files/61338737/VisualBasic6.doc