Documente Academic
Documente Profesional
Documente Cultură
2. When Microsoft Visual Basic starts, the New Project dialog box comes up:
At this time, we will not go through what all these icons mean. Just make sure that the Standard EXE icon is selected and click Open 3. A typical studio such as the one used by Visual Basic is referred to as an Integrated Development Environment (IDE). As a classic application, Microsoft Visual Basic displays a title bar on top. The title bar is mainly made of three sections. On the most left side, there is the application icon. This icon has a menu of its own. To see the menu, click the small icon and click Maximize (or Restore) 4. On the right side of the application icon, the name of the file allows to identify what you are working on. Microsoft Visual Basic names each one of its applications a project. A Project is a collection of files used to build a particular application. When Visual Basic starts, it calls the first application Project1. When you save a project, you give it an appropriate name, and the name on the title bar gets updated. On the right side of the Project1, the name helps to know what environment you are using to build your application. The Microsoft Visual Basic name is followed by the empty area of the title. This area can be used as a menu to maximize or restore a window. To experiment with it, double-click the empty section of the title bar. Notice that the window has been maximized (or restored) again
5. The last three buttons on the title bar are used to perform windows operations. Every one
of the buttons has a name. To find out a button's name, position your mouse on top of it and a name will appear. To experiment with the buttons, click the Minimize button
6. To bring back Microsoft Visual Basic, on the Task bar, click Project1.
7. Under the title bar, you have a menu made of words such as File, Edit, View, etc. These
allow you to perform almost any kind of operation. To use a menu, you click one of the words. A menu drops down and you make another selection from it. We need to review how a menu functions because as a programmer, you will have to create a menu or menus sooner or later. There are typically four kinds of menus here.
A disabled menu is a menu that is temporarily unavailable. This could be due to anything. For example, it might wait for another action to happen. Sometimes, there might be something running on the background and this would disable a function of your program or the application. To view an example of such menus, on the main menu, click Edit and observe a lot of disabled menus. To see another, position the mouse on Diagram and notice that the whole Diagram menu is disabled.
8.
An enabled menu standing by itself will usually perform a brief action, sometimes leaving the impression that nothing happened. This kind of menu can be used to quickly save a file, display a toolbar, etc. To see an example, on the main menu, click Edit -> Copy. It looks like nothing happened. The form (or if anything else was selected) has been copied to the clipboard, which is a temporary storage area of your computer.
9. To see another kind, on the main menu, click View -> Locals Window. Notice that there is a new section on the screen now.
10.
A menu with three periods () is typically used to launch or open a dialog box. To experiment with it, on the main menu, click Tools -> Options Notice that the Options dialog displays. sheet. From the Code Colors list box, click Normal Text. Click the Foreground combo box and select a green color. From the Code Colors list, click Selection Text. Click the Foreground combo box and select blue. Click the background combo box and select the lime color
11. The Options dialog is made of various property sheets. Click the Editor Format property
12. Click Comment Text. Click the Foreground combo box and select dark gray. Click Keyword Text. From the Foreground combo box, select blue. Click Identifier Text. From the Foreground combo box, select pink. 13. Click OK. At this time, we cannot yet experiment with the new settings.
14.
A menu with an arrow indicates that it has a sub-menu, which is a child menu. To see an example, on the main menu, click View -> Toolbars. Notice the items under the Toolbars menu.
15. To see another menu like that, position the mouse on Format -> Center In Form. 16. Whenever a menu is opened but you don't want to use it, you can dismiss it with the Esc key. To dismiss the current menu, press Esc. Press Esc again. 17. Some menu items present a key or a combination of keys on their line: this is called a shortcut. A shortcut is a key or a combination of keys that allows you or the user to perform an action quicker than using the menu. Some shortcuts can be seen on the menu of Visual Basic. Some other shortcuts are part of Microsoft Windows operating systems. To see a list of some of the shortcuts, on the main menu, click Edit. Observe the list of shortcuts and the actions they are associated with.
21. To use a combination of keys, press the first key (or one of the keys), and then press the other or others. Finally release the keys. To experiment with other shortcuts, press and hold Ctrl, then press F5. Notice that the form runs again as an application.
22. To close the running form, since it is treated as a complete application, press Alt + F4.
Some other shortcuts are part of the operating system. For example, Ctrl + Esc would open the Start menu; Alt + F4 is used to close applications.
23. Under the menu, there is a toolbar. This first toolbar is called the Standard toolbar.
The Standard toolbar allows you to perform many of the most common actions that would require the main menu, except that the toolbar is handier and closer to the user, which makes it faster. A toolbar is made of buttons that you click to perform the corresponding action. At first, nothing is obvious with these buttons. Therefore, to find out what a particular button is used for, position your mouse on top of it and keep it there for 2 seconds. A word and group of word will appear: this is the tool tip, allowing you to identify the button. The buttons are usually named after their tool tip. To get acquainted with some of the buttons, position your mouse on the first button for 1 or 2 seconds and observe the tool tip.
24. Move the mouse to another button and read the tool tip.
25. To experiment with one of the button, on the Standard toolbar, click the Start button
Notice that the form runs in its execution state.
26. To stop the running form, on the Standard toolbar, click the End button
27. Some of the buttons on the toolbar have an arrow on them. This indicates that the button, behaving like a menu or a combo box, can display more items when you click its arrow. To see an example, click the arrow of the Add Form button. Notice other items available. 28. Without clicking, move the mouse to the arrow of the first button on the toolbar, the Add Standard EXE Project button. 29. To dismiss the menu, click the arrow of the same menu. 30. The main area of the studio is made of a rectangular box called a form and is typically identified as Form1; if you create additional forms, by default, they would be identified as Form2, Form3, or FormX. 31. The Toolbox provides the necessary tools to create your applications.
The Toolbox comes with a lot of controls to start working. It can also be enhanced with more objects that we will review as we move on. Like the items on the Standard toolbar, the controls on the Toolbox are not always obvious. To find out what kind of control is displayed, position your mouse on a control and observe the tool tip. Review different items until you find the one you want. To use a control from the Toolbox, click it and draw it on your form. When no object is being used, the Pointer is selected. Once you select one of the controls, the pointer loses focus and you can use the selected control. We will learn how to use the controls in another lesson. Notice that the right section of the Standard toolbar displays the dimensions of the form.
32. The Properties Window displays a list of the properties associated with each control or
form that are part of your project. A property is anything that characterizes an object. When you look at a control, you see that it has a size, a color, a caption (something written on some controls; for example, on top of the form, the caption is Form1), etc. Different controls have different sets of properties. To experiment with controls properties, on the Properties Window, click the (Name) field and type frmTimeSheet Notice that even though you clicked (Name), the name has been changed.
37. To send the Code Editor window to the background again, on the Project Explorer window,
click the View Object button .
38. The Form Layout window allows you to position your form or forms with regard to the rest of the screen. It uses a graphical interface to guide you. To experiment with it, click the small image inside the small screen and drag to the upper left corner inside the small screen. Notice that the small image can move. 39. 40. Drag the small rectangle in the Form Layout screen again and position it to the middlw of the small screen. 41. To verify the result, press F5 to run the form. Notice that the running form displays in the center of the screen. 42. To close the running form, click its close button.
Saving a Project
A program you create in Microsoft Visual Studio (of course, this includes VB) is called a project. A Microsoft Visual Basic project is made of various objects that you create or add as your program grows. Therefore, when saving a program, you have to save the main project and its objects. There are two categorical pieces of information you should provide when saving a program: the project's location and a name for each object or file. The location is a folder where you store the program for easy retrieval when needed. A name for each component allows you to identify it as compared to other objects of the same program. An object's name can contain a combination of up to 255 characters. Refrain from using fancy characters. Assign a name made of characters a to z, A to Z, and digits 0 to 9.
5. On the Save File As dialog box, click the Create New Folder button 6. Type MS Visual Basic and press Enter twice to display the new folder in the Save In
combo box
again
8. Type Exercise1 and press Enter twice to display the new folder in the Save In combo box
9. In the File Name edit box, change the name of the file to frmMain and press Enter to
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
Next
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.
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 .
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.
Deleting Controls
If you have one of more controls that you don't need anymore, you can remove them from your form. To remove one control, select it and press Delete. To remove many controls, first select them, then press Delete. You can also select a control or a group of control, then rightclick and click Cut.
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.
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
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.
2. Notice that a tool tip displays the current coordinates of the control
As done with the location, there are various ways you can specify or control the dimensions of an object. If you click a control on the Toolbox, you can click and hold the mouse on the form then drag. While dragging, a rectangle would guide you with a tool tip that display the dimensions, live. Once you get the desired dimensions, you can release the mouse. If the control is already located on the form, to change its dimensions, after clicking it, position the mouse on one of its 8 handles. You would get one of the following cursors depending on where the mouse is located: Pointer Role Shrinks or heightens the control Resizes the control in North-East <-> South-West direction Narrows or widens the control Resizes the control in North-West <-> South-East direction You can also resize a control using the keyboard. To do this, click the control to select it. Then
press and hold Shift. While holding Shift, press: The down arrow key to heighten the control while its top border is locked The up arrow key to shrink the control while its top border is locked The right arrow key to widen the control to the right The left arrow key to narrow the control while its left border is locked
Once you reach the desired dimension, release Shift. You can also change the dimensions of a control to known values. To do this, after selecting the control on the form, in the Properties window, change the values of the Width and/or the Height fields. To change the dimensions programmatically, assign the desired values to its Width and/or Height properties. Not all controls can be resized. The controls that don't appear to the user, such as the Timer cannot be resized.
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
If a control displays text, it then has a Caption or a Text field in the Properties window. After adding such a control to a form, its Caption or its Text field may the same text as its name. At design time, to change the text of the control, click either its Caption or its Text field and type the desired value. For most controls, there are no strict rules to follow for this text. Therefore, it is your responsibility to type the right value. The text provided in a Caption or Text fields of a text-based control can only be set as is at during design. If you want the text to change while the application is running, you can format it. For example, such a control can display the current time or the name of the user who is logged in. These format attributes cannot be set at deign time. To change the text of a textbased control at run time, either assign a simple string or provide a formatted string to either the Caption or the Text property.
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.
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
Tab Sequence
When a form contains many controls, the user can navigate to different ones by clicking them. Alternatively, the user can press Tab to move the focus from one control to another. The controls that can be accessed using the Tab key belong to a group. For a control to participate to this group, it must have its TabStop property set to True. All graphical controls are automatically added to this group by default when they are picked from the Toolbox and added to a form. If you don't want a control to receive focus as a result of the user pressing Tab, set its TabStop to False. Each control in the Tab sequence group has a unique incremental number. This number is called TabIndex. The first control added receives a number of 0. The second receives 1, etc. The control whose TabIndex is the lowest would receive focus when the form comes up. If you want, you can change the default sequence by changing the TabIndex values of the controls.
Previous
Next
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.
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
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()
5. Press Enter
6. Notice that Visual Basic added the parentheses and the End Sub line 7. In the Code window, notice that the Object combo box is displaying Form
8. Click the arrow of the Object combo box to display its list:
9. Click the arrow of the Procedure combo box and, in the list, click MouseDown
10. Notice the section of the MouseDown event. Also notice that this event has a few arguments 11. We will eventually learn what the writings of these arguments mean. In the Object combo box, notice that Text1 is still displaying. 12. In the Code window, click on one of the form events. 13. Notice that the Object combo box has automatically changed.
Categories of Events
The Keyboard Events
Word processing consists of manipulating text and characters on your computer until you get the fantastic result you long for. To display these characters, you press some keys on your keyboard. If the application is configured to receive text, your pressing actions will display characters on the screen. The keyboard is also used to perform various other actions such as accepting what a dialog box displays or dismissing one. When you press the keys on your keyboard, you are sending keyboard events.
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.
3. Notice that after launching, WordPad is opened. Visual Basic says that WordPad is Loaded:
Previous
Next
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.
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.
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
11. Click OK
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.
Byte
A byte is a small natural positive number that r
= 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.
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.
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:
Caption Number
Name txtOperand
CommandButton Operation cmdOperation 7. Double-click the Operation button and implement its event as follows: Private Sub cmdOperation_Click() txtOperand = +248.64 End Sub 8. Press F5 to test the application 9. After using it, close the form
Unary Operators: The Negative Operator As you can see on the above ruler, in order to express any number on the left side of 0, it must be appended with a sign, namely the - symbol. Examples are -12, -448, -32706. A value accompanied by is referred to as negative. The - sign must be typed on the left side of the number it is used to negate. Remember that if a number does not have a sign, it is considered positive. Therefore, whenever a number is negative, it MUST have a - sign. In the same way, if you want to change a value from positive to negative, you can just add a - sign to its left.
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.
Name txtOperand1
2. Double-click the Addition button and change its code as follows: Private Dim Dim Dim Sub cmdAddition_Click() dblOperand1 As String dblOperand2 As String dblResult As String
dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 + " " + dblOperand2 txtResult = dblResult End Sub
3. Test the application. Enter a name one the First Name text box and another name in the
Last Name text box then click Addition
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.
Caption Number 1:
Name txtOperand1
dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 - dblOperand2 txtResult = dblResult End Sub
3. Test the application. Enter a number one the Number text box and another number in the
Number text box then click Subtraction
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
3. Double-click the Multiplication button and change its code as follows: Private Dim Dim Dim Sub cmdSubtration_Click() dblOperand1 As Double dblOperand2 As Double dblResult As Double
dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 * dblOperand2 txtResult = dblResult End Sub
4. Test the application. Enter a number one the Number text box and another number in the
Number text box then click Multiplication
3. Double-click the Division button and change its code as follows: Private Dim Dim Dim Sub cmdSubtration_Click() dblOperand1 As Double dblOperand2 As Double dblResult As Double
dblOperand1 = txtOperand1 dblOperand2 = txtOperand2 dblResult = dblOperand1 \ dblOperand2 txtResult = dblResult End Sub
4. Test the application. Enter a number one the Number text box and another number in the
Number text box then click Division
Logical Comparisons
Logical Operations
Introduction
Sometimes while a person is using your program, you may need to check whether something is true or it is false. This type of operation is performed using operators referred to as comparison operators. Visual Basic provides various operators that can be used in appropriate types of comparisons.
Boolean Variables
The Boolean data type is used to declare a variable whose value would be set as true (1) or false (0). To declare such a value, you use the Boolean keyword. The variable can then be initialized with a starting value. The Boolean constant is used to check that the state of a variable (or a function) is true or false. You can declare such a variable as: dim GotThePassingGrade as Boolean; Later in the program, for a student who got a failing grade, you can assign the other value, like this GotThePassingGrade = False;
Logical Operators
Equality =
To compare two values for equality, use the = operator. Its formula is: Value1 = Value2 The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. From our formula, the compiler would compare the value of Value1 with that of Value2. If Value1 and Value2 hold the same value, the comparison produces a true result. If they are different, the comparison renders false or 0.
Here is an example: Private Sub Command1_Click() Dim value As Integer value = 15 Text1.Text = "Comparison of Value = 32 produces " & (value = 32) End Sub
The result of a comparison can also be assigned to a Boolean variable. Here is an example: Private Sub Command1_Click() Dim value1 As Integer Dim value2 As Boolean value1 = 15 value2 = (value1 = 32) Text1.Text = "Comparison of Value = 32 produces " & value2 End Sub
Logical Not
When a variable is declared and receives a value (this could be done through initialization or a change of value) in a program, it becomes alive. It can then participate in any necessary operation. The compiler keeps track of every variable that exists in the program being processed. When a variable is not being used or is not available for processing (in visual programming, it would be considered as disabled) to make a variable (temporarily) unusable, you can nullify its value. To render a variable unavailable during the evolution of a program,
apply the logical not operator which is Not. Its formula is: Not Value There are two main ways you can use the logical Not operator. As we will learn when studying conditional statements, the most classic way of using the logical Not operator is to check the state of a variable. To nullify a variable, you can write Not to its left. When used like that, you can display its value. You can even assign it to another variable. Here is an example: Private Sub Command1_Click() Dim value1 As Integer Dim value2 As Boolean value1 = 250 value2 = Not value1 Text1.Text = value2 End Sub When a variable holds a value, it is "alive". To make it not available, you can "not" it. When a variable has been "notted", its logical value has changed. Therefore, you can inverse the logical value of a variable by "notting" or not "notting" it. This is done by typing Not to its left.
Inequality <>
Visual Basic provides an operator used to compare two values for inequality. Its formula is: Value1 <> Value2 <> is a binary operator (like all logical operators except the logical Not, which is a unary operator) that is used to compare two values. The values can come from two variables as in Variable1 <> Variable2. Upon comparing the values, if both variables hold different values, the comparison produces a true or positive value. Otherwise, the comparison renders false or a null value.
Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean
value1 = 212 value2 = -46 value3 = (value1 <> value2) Text1.Text = value1 & " <> " & value2 & " = " & value3 End Sub
Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean
value1 = 212 value2 = -46 value3 = (value1 < value2) Text1.Text = value1 & " < " & value2 & " = " & value3 End Sub
Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean
value1 = 212 value2 = -46 value3 = (value1 <= value2) Text1.Text = value1 & " <= " & value2 & " = " & value3 End Sub
Here is an example: Private Dim Dim Dim Sub Command1_Click() value1 As Integer value2 As Integer value3 As Boolean
Text1.Text = value1 & " > " & value2 & " = " & value3 End Sub
Here is an example:
Text1.Text = value1 & " >= " & value2 & " produces " & value3 End Sub
Here is a summary table of the logical operators we have studied: Operator Meaning Example Opposite = Equality to a=b <> <> Not equal to 12 <> 7 = < Less than 25 < 84 >= <= Less than or equal to Cab <= Tab > > Greater than 248 > 55 <= Greater than or equal >= Val1 >= Val2 < to
Previous
Next
Conditional Statements
Overview of Conditions
Introduction
The essence of computer programming relies on telling the computer what to do when something occurs, and how to do it. This is performed by setting conditions, examining them and stating what decisions the computer should make. Microsoft Visual Basic uses various conditional statements for almost any situation your computer can encounter. As the application developer, it is up to you to anticipate these situations and make your program act accordingly.
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
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
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.
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.
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.
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 Disjunction: OR
A logical disjunction is performed on two conditions for a single truthfulness. This operation uses the OR keyword on the following formula: Condition1 OR Condition2 The left condition, Condition1, is first checked. If Condition1 is True, then the whole expression is true, regardless of the outcome of the second. If Condition1 is False, then Condition2 is checked. If Condition2 is True, the whole expression is True even if Condition1 is False. In the same way, if both conditions are True, the whole expression is True. The whole expression is false only if both Condition1 and Condition2 are False. This can be resumed as follows: Condition1 True Don't Care True False Condition2 Don't Care True True False Condition1 OR Condition2 True True True False
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.
Previous
Next
1. Start Visual Basic and, in the opening dialog box, double-click Standard EXE 2. To save the project, on the main menu, click File -> Save Project 3. Locate your MS Visual Basic folder created in the first lesson and display it in the Save In combo box
4. In the Save File As dialog box, click the Create New Folder button 5. Type Modules1 and press Enter twice to display the new folder in the Save In combo box 6. Replace the name of the file in the File Name edit box with Main and press Enter 7. Type Modules1 to replace the name of the project and press Enter. If are asked whether
you want to add the project to SourceSafe, click No 8. Display the form and design it as follows:
Control Label TextBox Label TextBox Button Label TextBox Button 9. Save all
Name
Caption Side:
txtSide
0.00 Perimeter:
txtPerimeter
0.00
cmdCalcPerimeter Calculate Area: txtArea cmdCalcArea 0.00 Calculate Alignment: 1-Right Justify
Creating a Module
There are two main ways you obtain a module for your program. When you create a form, a module is automatically created and associated to it. You can access the module of a form by right-clicking it and click View Code. Besides the modules created for your forms, you can create your own modules any time. To create a new module, on the main menu, you can click Project -> Add Module. In the Add Module dialog box, you can click Open. Once a new module
has been added to your project, it is treated as a file. As such, you should save it to give it a friendlier name. The name of a module can be used to indicate the type of code included in that module. Once a module is ready, you can type any piece of valid code in it. Such a module is automatically made available to other parts of your program. Just as you can write code in a module attached to a form, you can also write code in an independent module (unlike some other languages like C/C++ or Pascal, you usually don't need to reference one module from another; once a module has been created, you can use its contents as you wich). Any existing module of your project is represented in the Project window with a button and a name in the Modules node. Therefore, to open a module, in Project window, you can doubleclick its node.
2. To create a new module, on the Standard toolbar, click the arrow of the Add Form button
and click Module
3. In the Add Module dialog box, make sure the Module icon is selected and click Open
4. To save the new module, on the Standard toolbar, click the Save button 5. Change the name of the file to modGeometry and press Enter 6. To change the name of the module in Visual Basic, in the Project window, click Module1.
In the Properties window, click (Name). Type Routines and press Enter
Procedures
A procedure is an assignment you ask the compiler to take care of inside of your program. The assignment is performed behind the scenes. The program developer writes the function and the user would only see the result. In reality, there are two types of procedures you will use in your programs: those that have already been created thus made available to you, and those you will create yourself. In Visual Basic, like most other languages, there are two categories of procedures: functions and sub routines (many other languages like Pascal make this distinction; some other languages like C++, C#, etc use only the name function to identify both categories).
Sub Routines
Introduction
As mentioned already, there are differences between a function and a sub routine. A sub routine is an assignment that is carried but doesn't give back a result. To create a sub routine, start by typing the Sub keyword followed by a name because, like everything else, a procedure must have a name. The name of a procedure is always followed
by parentheses. At the end of the sub routine, you must type End Sub. Therefore, the syntax of a sub routine is: Sub ProcedureName() End Sub You can also initiate a sub routine by asking Visual Basic to generate one for you. To do that, on the main menu, you can click Tools -> Add Procedure... In the Add Procedure dialog box, specify a name for the procedure. Make sure the Sub radio button is selected and click OK. The name of a procedure should follow the same rules we learned to name the variables, omitting the prefix: If the procedure performs an action that can be represented with a verb, you can use that verb to name it. Here are examples: show, display To make the name of a procedure stand, you should start it in uppercase. Examples are Show, Play, Dispose, Close You should use explicit names that identify the purpose of the procedure. If a procedure would be used as a result of another procedure or a control's event, reflect it on the name of the sub procedure. Examples would be: afterupdate, longbefore. If the name of a procedure is a combination of words, you should start each word in uppercase. Examples are: AfterUpdate, SayItLoud
The section between the Sub and the End Sub lines is referred to as the body of the procedure. The body of the procedure is used to define what and how the assignment should be carried. For example, if you need to use a variable, you can declare it and specify what kind of variable you need. There is no restriction on the type of variables that can be declared in a procedure. Here is an example in which a string variable is declared in the body of a sub routine: Sub Assignment() Dim strFullName As String End Sub In the same way, you can declare as many variables as you need inside of a procedure. The actions you perform inside of a procedure depend on what you are trying to accomplish. For example, a procedure can simply be used to create a string. The above procedure can be changed as follows: Sub Assignment() Dim strFullName As String strFullName = "Paul Bertrand Yamaguchi" End Sub
End Sub 2. To create another sub routine, on the main menu, click Tools -> Add Procedure...
4. Click OK 5. Implement both routines as follows: Sub SquarePerimeter() Dim dblSide As Double Dim dblPerimeter As Double dblSide = Form1.txtSide dblPerimeter = dblSide * 4 Form1.txtPerimeter.Text = dblPerimeter End Sub Public Sub SquareArea() Dim dblSide As Double Dim dblArea As Double dblSide = Form1.txtSide dblArea = dblSide * dblSide Form1.txtArea.Text = dblArea End Sub 6. Save all
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
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.
Control Label TextBox Label TextBox Button Label TextBox Label TextBox 2. Save all
Name
Caption Length:
txtLength
0.00 Height:
txtHeight
txtPerimeter
0.00 Area:
txtArea
0.00
Function Creation
To create a function, you use the Function keyword followed by a name and parentheses. Unlike a sub routine, because a function returns a value, you should/must specify the type of value the function will produce. To give this information, on the right side of the closing parentheses, type the As keyword, followed by a data type. To indicates where a function stops, type End Function. Based on this, the minimum syntax used to create a function is: Function FunctionName() As DataType End Function The name of a function follows the same rules and suggestions we reviewed for sub routines. The DataType factor indicates the type of value that the function will return. If the function will produce a word or a group of words, you can create it as String. If the function will check something and determine whether it produce a true or a false value, you can create it as Boolean. The other data types are also valid in the contexts we reviewed them. As mentioned already, the section between the Function and the End Function lines is the body of the function. It is used to describe what the function does. As done on a sub routine, one of
the actions you can perform in a function is to declare a (local) variable and use it as you see fit. Here is an example: Function CallMe() As String Dim Salute As String Salute = "You can call me Al" End Function After performing an assignment in a function, to indicate the value it returns, somewhere after the assignment and before the End Function line, type the name of the function, followed by the = sign, followed by the value the function returns. Here is an example in which a function returns a name: Function CallMe() As String CallMe = "You can call me Al" End Function You can also use some local variables in the function to perform an assignment and then assign their result to the name of the function. Here is an example: Function CallMe() As String Dim Salute As String Salute = "You can call me Al" CallMe = Salute End Function
2. To create a new function, at the end of the file, type function RectPerimeter and press
Enter 3. To create another function, on the main menu, create Tools -> Add Procedure...
4. In the Name edit box, type RectArea 5. In the Type section, click Function
6. Press Enter
7. Implement both functions as follows: Function RectPerimeter() Dim dblLength As Double Dim dblHeight As Double dblLength = Form1.txtLength.Text dblHeight = Form1.txtHeight.Text RectPerimeter = (dblLength + dblHeight) * 2 End Function Public Function RectArea() Dim dblLength As Double Dim dblHeight As Double dblLength = Form1.txtLength.Text dblHeight = Form1.txtHeight.Text RectArea = dblLength * dblHeight End Function 8. Save all
Calling a Function
As done for the sub routines, in order to use a function in your program, must call it. Like a sub routine, to call a function, you can simply type its name in the desired section of the program. Here is an example: Private Sub Form_Load() CallMe End Sub Since the primary purpose of a function is to return a value, to better take advantage of such a value, you can assign the name of a function to a property or a variable in the section where you are calling the function. In the following example, the return value of the CallMe function is assigned to the Caption property of the form from its own Load event: Private Sub Form_Load() Caption = CallMe End Sub
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.
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
dblLen = txtLength.Text dblHgt = txtHeight.Text dblPerim = RectPerimeter(dblLen, dblHgt) dblArea = RectArea(dblLen, dblHgt) txtPerimeter.Text = dblPerim txtArea.Text = dblArea
End Sub
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.
txtPerimeter.Text = dblPerim txtArea.Text = dblArea End Sub 4. Test the application 5. Close the form
Previous
Next
Built-In Functions
Overview of Built-In Procedure
Introduction
A procedure is referred to as "built-in" if it shipped with your language. To make your job a little easier, Microsoft Visual Basic comes equipped with many functions that you can use right away in your program. Based on this, before creating your own function, first check whether the functionality you are looking is already implementing in one of the available procedures because those that ship with Visual Basic are highly reliable and should be preferred. Before using a built-in procedure, you must of course be familiar with it. This comes either by consulting the documentation or by experience. This means that you must know its name, its argument(s), its return value, and its role.
Conversion Functions
The first action you should take when dealing with a value or an expression is to convert it to the appropriate type. There are various conversion functions adapted to the different possible kinds of values. The general syntax of the conversion functions is: ReturnType = FunctionName(Expression) The Expression could be of any kind. For example, it could be a string or value the user would have entered in a form. It could also be the result of a calculation performed on another field or function. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax.
Function Name CBool CByte CDate CDbl CInt CCur CLng CSng CStr Return Type Boolean Byte Date Double Integer Currency Long Single String Description Converts an expression into a Boolean value Converts an expression into Byte number Converts and expression into a date or time value Converts an expression into a flowingpoint (decimal) number Converts an expression into an integer (natural) number Converts an expression into a currency (monetary) value Converts an expression into a long integer (a large natural) number Converts an expression into a flowingpoint (decimal) number Converts an expression into a string
2. Here are the names of the controls (the three left labels provided "as is"): (Name) Caption (Name) frmOperations Operations fraOperations lblMainTitle Algebraic Operations optAddition txtNumber1 optSubtraction
txtNumber2 txtResult
Result
4. On the Object combo box, select optAddition. 5. Since its default event is Click, implement it as follows: 6. Private Sub optAddition_Click() 7. Dim dblNumber1 As Double 8. Dim dblNumber2 As Double 9. Dim dblResult As Double 10. 11. dblNumber1 = CDbl(txtNumber1.Text) 12. dblNumber2 = CDbl(txtNumber2.Text) 13. dblResult = dblNumber1 + dblNumber2 14. 15. txtResult.Text = dblResult End Sub 16. Implement the Click event of the other option buttons the (exact) same way, only changing the sign in the dblResult line. Here is the code: 17. Private Sub optDivision_Click() 18. Dim dblNumber1 As Double 19. Dim dblNumber2 As Double 20. Dim dblResult As Double 21. 22. dblNumber1 = CDbl(txtNumber1.Text) 23. dblNumber2 = CDbl(txtNumber2.Text) 24. dblResult = dblNumber1 / dblNumber2 25. 26. txtResult.Text = dblResult 27. End Sub 28. 29. Private Sub optMultiplication_Click() 30. Dim dblNumber1 As Double 31. Dim dblNumber2 As Double 32. Dim dblResult As Double 33. 34. dblNumber1 = CDbl(txtNumber1.Text) 35. dblNumber2 = CDbl(txtNumber2.Text) 36. dblResult = dblNumber1 * dblNumber2 37. 38. txtResult.Text = dblResult 39. End Sub 40. 41. Private Sub optSubtraction_Click() 42. Dim dblNumber1 As Double 43. Dim dblNumber2 As Double 44. Dim dblResult As Double 45. 46. dblNumber1 = CDbl(txtNumber1.Text) 47. dblNumber2 = CDbl(txtNumber2.Text) 48. dblResult = dblNumber1 - dblNumber2 49. 50. txtResult.Text = dblResult End Sub
51. To test the form, press F5. 52. Please, make sure you type a number, and a number other than 0, in the Second Number text box, especially before clicking the Division option button. This is because we didn't write a conditional statement that would check the content of those text boxes, and we know that it is "nasty" to divide a number by 0. Conditional statements will be studied later: one lesson at a time
String-Based Functions
Introduction
A string-based function is one that deals with functions; either it manipulates them or returns them. Microsoft Visual Basic allows you to be specific about the return value you are expecting. Some of the functions you will be using can be configured to return exactly a string. Such functions use the $ suffix that states it clearly.
Message Boxes
A message box is a special form used to display a piece of information to the user. As opposed to a regular form, the user cannot type anything on the box. There are usually two kinds of dialog boxes you will create: one that simply displays information and one that expects the user to make a decision. To create a message box, you can use the MsgBox function. There are two techniques to use it. To display a simple message with just an OK button, use the MsgBox method whose syntax is MsgBox Message The parameter, Message, is the string to present to the user. As a normal, it should be passed in double-quotes. Here is an example: Private Sub Form_Load() MsgBox "Welcome to the wonderful world of Microsoft Visual Basic" End Sub When the above version of the the MsgBox function is used, a rectangular form (we will learn later on that this type of form is called a dialog box) is presented to the user, display a string message and an OK button:
Another version of the MsgBox function allows you to present a message that asks a question to the user, expecting a decision. This version displays a more informative prompt with more than one button. The user makes a decision by clicking one of the presented buttons. After the user has clicked a button, you can then retrieve the result and use it as you see fit. The syntax
of this version is: MsgBox Message, [Buttons], [Title], [HelpFile], [Context] The Message argument is the string that the user will see displaying on the message box. As a string, you can display it in double quotes. You can also create it from other pieces of strings. The Message argument can be made of up to 1024 characters. To display the Message on multiple lines, you can use either the constant vbCrLf or the combination Chr(10) & Chr(13) between any two strings. Besides the Message parameter, this version allows you to display more than one button. If you don't need to, you don't have to specify the buttons. If you don't, the message box would appear with only an OK button. Otherwise, you can specify what buttons to display. This is done using the Buttons argument. There are different kinds of buttons available and Visual Basic recognizes them by a numeric value assigned to each. The buttons are Button vbOKOnly vbOKCancel vbAbortRetryIgnore vbYesNoCancel vbYesNo vbRetryCancel Value 0 1 2 3 4 5 Display
Here is an example of a message box that display a Yes and a No buttons: Private Sub Form_Load() MsgBox "Are you ready to rumbleeeeeeeeeee", vbYesNo End Sub This would produce:
When a message box displays more than one button, one of the buttons usually has a thick button. That button is also called the default button. If the user presses Enter upon reading the message, the compiler would behave as if the default button was clicked. There are some buttons that are set automatically as default when you create the message box. If you don't like the set button to be the default, you can specify which one you prefer as default. To do that combine a second value with one of the above values for the buttons. You can set the default argument using the following table Option Value
Parent Controls
Characteristics of Parent Controls
Introduction
An object is referred to as parent when it can carry or host other objects, acting as their parent. When you start the computer, the first object the operating system creates is the desktop window. This is a wide rectangular area that covers the entire monitor screen. Based on the settings of the Control Panel, the operating system uses either a color or a picture (a bitmap) to fill the window. Once the desktop is ready, other objects or controls can be placed on it. The desktop is the parent of all other objects that display on the screen. To provide some information about the desktop, you can use an object called Screen. This allows you to get such details as the screen dimensions (its width and height), the form that is displaying on the screen, the list of fonts in the computer, etc. A control is referred to as container if it can host other controls. While the desktop is the main container of the computer, to develop your applications, you will use your own controls that can act as parent to other controls. Examples of such controls include the form, the frame, the picture box, the status bar, the toolbar, etc. The list is impressive and these parent controls are usually used for different purposes. In fact, the only real characteristic they share is their ability to host other controls. Except for the form (and consequently the dialog box), most, if not all, of the other containers must be hosted by a form. Therefore, after starting a project or once you get a form, you can place a control container on it (the form). Once placed on a form, these parent windows can host their own controls. Therefore, to use a container, you can either position your control on the form, in which case the form would act as the parent, or you can first select one of the containers, place it on a form, and then add other controls to it.
Cartesian coordinate system whose origin is on the top-left corner of the screen. The horizontal axis moves from the left border to the right. The vertical axis moves from the top border down. The distance from the left border of the screen to the left border of the form is called the Left property. The distance from the top border of the screen to the top border of the form is its Top property. This can be illustrated as follows: The above illustration shows a form positioned on a monitor. The desktop acts as the parent window of the form. In the same way, if you place a control on a container, the control is located with regards to its parent, not based on the screen. As seen previously, in such a case, the origin of the coordinate system is located on the top-left corner of the parent window. The distance from the left border of the parent window to the left border of the control is the controls Left property. The distance from the top border of the parent window to the top border of the control is the controls Top property. Here is an example in which a control as a child is positioned inside of another control that acts as its parent:
The desktop window provides a rectangular area that it can use to display the computers applications. This area is also used to host other objects. Although an objects borders can span beyond the borders of the desktop, only the area of an object covered by the desktop can be seen. Here is an example of a window whose right side cannot be seen:
The client area is a rectangle primarily used for its location and dimensions. To get the values of the shape that compose the client area, you have various options and considerations. For example, to get the area that represents the desktop, which would let you know how much real estate is available for your application, you can call the Screen.Width and/or Screen.Height variables. It is important to know where the origin of a control is located. During control design, we saw that, when a container is selected and you double-click a visual control on the Toolbox, the new control would be added to the container. On the other hand, if you have a container that is positioned on the form but the container, or any specific container, is not selected, if you double-click a control on the Toolbox, the control would be added to the form even though the new control may be positioned on a container. In this case, the form would become the parent of the new control. Therefore, in order to do anything related to the location and/or dimensions of a control, you must know the coordinate of the origin used as the basis for its location and dimensions. Because only a parent can host some controls, it holds an origin and makes it available to its children.
Forms
Introduction
A form is a rectangular object that can be used as a program of its own, it is also usually used as part of a bigger application. The form is a window control that mostly serves as a place holder for other controls. There are two main ways you create a form: as its own program or as part of an application. Whenever you launch Microsoft Visual Basic, the opening dialog offers to create a form. To add a form into an existing program, on the main menu, you can click Project -> Add Form. When creating a form, you can control its properties at design time using the Properties window. Many of these properties can be set at run time with code. A form can control its own properties when an event related to a form is fired. A form's properties can also be set or changed using other controls on the form itself or controls from another form or from the computer (for example, you can control a property based on the system time of the computer).
2. To change the name of the form, in the Properties window, click (Name) and type frmMain
3. To test the application, press F5
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.
This technique allows you to position the form with a good approximation. Alternatively, after selecting the form in design, in the Properties window, change the value of the StartUpPosition property. The options are: StartUpPosition 0 - Manual Description Allows you to specify the position of the form using the rectangle in the Form Layout window If this is the first or main form, its parent is the desktop. Therefore it would be positioned in the center of the screen. If this is the second form, it would be positioned in the center of the form used to display it This form will be centered with regards to the desktop The application will let the operating system specify the position of the form
1 - CenterOwner
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.
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.
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
26. After viewing the form, to close it, click its Close button
27. Notice that the form is back to the dimensions set in the Properties event.
28. To use another event, on the Project window, click the View Code button 29. In the Code window, make sure that Form is displaying in the Object combo box.
Click the arrow of the Procedure combo box and select DblClick:
30. Write the code of the DblClick event as follows: 31. Private Sub Form_DblClick() 32. Me.Caption = "You double-clicked Me!" End Sub 33. To test the form, on the main menu, click Run -> Start. 34. After viewing the form, to close it, on the main menu, click Run -> End.
35. To add another form to the project, on the Standard toolbar, click the Add Form button
36. From the Add Form dialog box, make sure the Form icon is selected and make sure the check box is not checked. Click Open.
37. As the new form is displaying, in the Properties window, click (Name) and type
frmEmployees
38. Double-click BorderStyle a few times (it should take only one double-click) until it
displays 3 - Fixed Dialog
39. Click Caption and type Employees Records 40. We will display this form when the user double-click in the center (or an empty area) of
the first form. In the Project window, double-click frmControls
41. In the Code window, make sure that Form is displaying in the Object combo box. Change the code of the DblClick event as follows: 42. Private Sub Form_DblClick() 43. Me.Caption = "You double-clicked Me!" 44. frmEmployees.Show End Sub
45. To save the project, on the main menu, click File -> Save Project.
46. To test the project, on the Standard toolbar, click the Start button
47. To display the other form, double-click in the displayed form. 48. Notice that the other form displays.
Frames
A frame is used as a place holder for other controls; therefore, it is called a container. You can insert any kind of control in a frame, including labels, text box, command buttons, and even other controls. The controls inside of a frame are treated as a group; as we will see, some of their settings can be changed together at once.
Practical Learning: Creating A Frame 1. To create a new project, on the main menu, click File -> New Project. If you are asked to save the current project, click No. 2. On the New Project dialog box, click Standard EXE and click OK. 3. Change the form's size to 4875 x 4725. 4. Change the the Border Style to 3 - Fixed Dialog 5. On the Toolbox, double-click Label 6. On the Properties Window, make the following changes: (Name) Alignment Caption Font lblMainTitle Height 2 - Center Left College Park Auto Parts Top Times New Roman, Bold, 16 495 120 120 4335
7. On the Toolbox, double-click Frame 8. On the Properties window, make the following changes: (Name) fraMake Top 720
Visible Width
True 2055
Previous
Next
Primary Controls
Microsoft Visual Basic
Command Buttons
A command button is a control that allows the user to make a decision based on what the form is displaying. This could be a simple acknowledgement such as a form displaying a quick message to the user. It could also require the user to make other selections or perform some settings on a dialog box before continuing to other issues. As a programmer, the computer and the user count on you to decide on the role of a button. And as stated already, a button can assume any role you assign it to.
3. To test the form, press F5 (of course, the button doesn't do much because we didn't ask it to do anything). 4. There are many ways you can access the area where you will be writing code. Usually, the code you write will be associated with one of the controls on your form. Although many behaviors are associated with each control, every control, including the form itself, has a
default behavior. For example, the default behavior of a button is the click action. To access the code associated with the first button, double-click Employees. This opens the Code Editor window. 5. Notice that the mouse cursor is inside of the click event code associated with the cmdEmployees button. Change the code of the event as follows: 6. Private Sub cmdEmployees_Click() 7. frmEmployees.Show End Sub
8. To test the effect of the new code, on the Standard toolbar, click the Start button
9. When the main form is loaded, click the Employees button. Notice that the second displays.
10. To close the Employees Records form, click its Close button
11. Notice that the caption did not change on the main form, although it would change if you had double-clicked inside of the form.
14. On the Properties window, make the following changes: (Name) Caption Height cmdExit Exit 375 Left Top Width 3480 3120 1215
15. Earlier you saw that when a form is loaded, if you click the End button
on the Standard toolbar, the form is closed. Now, we will write code that will tell Microsoft Visual Basic that when we click the Exit button, we want it to behave as if we had clicked the End button on the Standard toolbar. On the main form, double-click the Exit button.
16. Press Tab and type End so your code appears as follows:
17. Private Sub cmdExit_Click() 18. End End Sub
19. To test the functionality of the form as this time, on the Standard toolbar, click the Start
button 20. Click the Employees button
21. To close the Employees Records form, click its close button
22. To close the main form, click Exit.
23. To save the project, on the main menu, click File -> Save Project
Labels
A label is a control used to display text on a form. This control is for two main purposes: to provide quick information or to help the user identify another control on the form. The properties of a label are completely under your control; the user cannot manipulate them. Although you can change these properties at will, make sure you set their appropriate values in the Properties window. Always avoid distracting the user.
Practical Learning: Creating A Label 1. To create a new project, on the main menu, click Filed -> New Project 2. On the opening dialog box, make sure Standard EXE is selected and click Open. 3. On the Toolbox, click Label. 4. On the form, draw a rectangular box from the top left section to the right section.
7. Click Caption and type Rockville Auto-Mart 8. Click the Font field. Click its Build button 10. Click Height and type 495 11. Click Left and type 120 12. Click Top and type 120 13. Click Width and type 4500 14. To test the form, press F5 15. To close the running form, click its close button
16. On the Toolbox, double-click Label. 17. Using the label's handles, move it under the main title and on the left. 18. By double-clicking and moving the controls, create the following four labels: (Name) Caption Height Left Top Width lblFirstName First Name 255 120 705 855 lblLastName LastName 255 120 1125 855 lblFullName Full Name 255 120 1560 855 lblMessage Empty 255 120 2160 3975 . to call the Font dialog box.
9. On the Font dialog box, set the font to Times New Roman, Style = Bold, and Size = 22.
Text Boxes
A text box is used to receive information from the user by her typing it into this box. A text box can also be used to simply display information to the user. Although a text box is a good control by itself, it usually doesn't mean much to the user if she doesn't know what the box is used for. Therefore, you should always create a text box in conjunction with a label. The label is used to identify what the text is used for. You should position the label on the left or on top of the text box. The rules of using the computer suggest that a text box be identified by the caption of its label. For example, if a label displays First Name:, the text box on its right would be called The First Name Text Box. If a labels displays How Old Are You?, its corresponding text box would be called The How Old Are You Text Box. But remember, programmatically, the text box and its label are completely independent. Practical Learning: Adding A Text Box 1. On the Toolbox, double-click TextBox. 2. On the form, drag the text box up a little bit to move it up. 3. By double-clicking, add three more boxes. 4. On the Properties window, make the following changes (Name) Height Left Text Top Width txtFirstName 285 1080 Empty 705 1815 txtLastName 285 1080 Empty 1125 1815 txtFullName 285 1080 Empty 1560 1815
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
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
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.
2. On the form, click on the right section of the form but outside of the existing frame and drag right a little bit. 3. On the Properties window, make the following changes: (Name) Caption Height Left fraFord Ford 1575 2280 Top Visible Width 720 True 2055
4. On the Toolbox, click the CheckBox. 5. On the form, click and drag inside of the right frame. For this exercise, you don't need to be precise when dragging but make sure you draw only inside of the right frame. 6. On the Properties window, change the name of the check box to chkFocus and change its caption to Focus. 7. From the Toolbox, draw another check box inside of the left frame but under the first check box. 8. Change the name of the new check box to chkEscort and its caption to Escort 9. From the Toolbox, draw another check box inside of the left frame but under the second check box. 10. Change the name of the new check box to chkTaurus and its caption to Taurus 11. To test the form, press F5
Previous
Next
List-Based Controls
Combo Boxes
Introduction
A combo box is a window control that presents a list of items the user can select from. Visually, a combo box looks like a text box equipped with a down pointing arrow on its right side. By default, a combo box displays an item. In order to change the content of that box,
different options are available. You cam allow the user to type in the combo box and try to match what the user types with one of the items in the list. You can also make the user only select an item from the list by clicking the down pointing arrow. You can also display the list at all times and let the user select an item from the list. If the list is long and cannot display everything at the same time, a combo box is equipped with a vertical scroll bar. To create a combo box, from the Toolbox, you can (1) double-click it or (2) click it once and draw on the form. Once you have a combo box on your form, it is important that you change its name to a more meaningful one. One of your first concerns with combo boxes is to decide what it will display or what it will be used for. Then provide a list of its items. When designing a combo box, you can use the List field to provide a list of its items. This allows you to create a list of items you know already. To create such a list, click the arrow of the List field, type an entry, press Ctrl + Enter, type the next item, and continue like that until you have provided the items desired. To programmatically create a list of items for a combo box, first decide when the list should be filled up, using one of the events. Then use the AddItem method to create the necessary list. Most of the time, you will decide to fill a list when the form Loads.
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.
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.
34. On the Properties window, change the name of the new combo box to cboWeekdays
35. Double-click an empty area of the form to access the form's load event. 36. Implement the event as follows: 37. Private Sub Form_Load() 38. cboWeekdays.AddItem "Sunday" 39. cboWeekdays.AddItem "Monday" 40. cboWeekdays.AddItem "Tuesday" 41. cboWeekdays.AddItem "Wednesday" 42. cboWeekdays.AddItem "Thursday" 43. cboWeekdays.AddItem "Friday" 44. cboWeekdays.AddItem "Saturday" 45. cboWeekdays.Text = "Monday" End Sub
46. To test the form, press F5 47. To close the running form, click its close button
.
List Boxes
A list is a control that presents a list of items to the user who can make his selection by clicking on the list. Depending on how the list is configured, the user can click one item at a time or select many items from the list.
Practical Learning: Creating A List Box 1. Create a new Standard EXE project 2. Give the form a size of 4800 x 2715
3. From the Properties section, click the (Name) box and type frmCountries 4. Change the the Border Style to 3 - Fixed Dialog and its Caption to Type Country Selection
5. From the Toolbox, click ListBox. 6. On the form, draw a box from 120, 120 to 2055 x 2010. 7. In the Properties section, click the (Name) and type lstCountry 8. Scroll down and click ToolTip Text. Type Double-click a country 9. From the Components toolbar, click the TextBox. 10. On the form, draw a box from 2400,120 to 2055 x 375 11. Scroll up in the Properties and click Name. Type txtCountry 12. Scroll down in the properties list and click in the Text field. delete the content of that Text field 13. From the Components toolbar, click the CommandButton 14. On the form, draw a box from 2400, 120 to 2055 x 375 15. In the Properties section, click the (Name) field and type cmdCountryChoice
for a command button which is the Click event, because that's what users mainly do to a button. 29. Edit the Click event as follows: 30. Private Sub cmdCountryChoice_Click() 31. txtCountry.Text = lstCountry.Text End Sub 32. Click the Object combo box and select lstCountry. That initializes the events for the list box. 33. The default event of the list box is the Click because that is the first thing users think of doing on a list box. In this case we would like to get a double-clicked item from the user and display the double-clicked item in the text. All we need to do is ask the double-clicked list box to behave as if the cmdCountryChoice Click the Procedure combo box and select DblClick 34. Edit the Double Click procedure as follows 35. Private Sub lstCountry_DblClick() 36. cmdCountryChoice.Value = True End Sub 37. To test the form, on the Standard toolbar, click the Start button 38. Double-click Costa Rica. Double-click Greece. Notice that the country double-clicked displays in the text box. 39. Click Thailand, then click the button. Click Cote D'Ivoire and click the button. Notice that this action has the same effect as double-clicking the country.
40. To test the form, press F5 41. To close the running form, click its close button
.
Previous