Learn Visual Basic
Difficulty:   Lessons: 1, 2, 3, 4, 5

by Lorenzo Dalla Vecchia

Introduction to Events and Code

In the last two lessons, we focused our attention on the creation of the interface of the program, mainly on the creation of controls and the setting of their properties. Now you will start to learn how to tell your program what to do in response to particular events, such as the clicking of a button.

When programming, you will spend the most of your time writing code: the code is a sequence of commands you write that tell the program what to actually do (calculations, for example); the code must be written in the Visual Basic language.
Vb is defined as an event-driven language: that means that the code is split into many pieces that are executed independently on the verifying of actions by the user. The actions you can associate code to are called Events.

Each control has its own events: command buttons have the Click event (that is triggered each time the user clicks on the button itself), forms have the Load event (triggered when the form is started). By attaching code to those events, you can make the application do whatever you want.

Now, let's see how to attach code to events:

  1. Double-click on a control to access its events
  2. The Form View area of the screen will be replaced by the Code View, where you can type code into. Note that there are two dropdown lists on the top of the Code View.
    The first indicates the control you have just selected: you can use that list to switch to another control without returning to the Form View.
    The second indicates the currently selected event and all the code shown in the inferior area refers to that event: use that list to switch to other control events (controls usually have a lot of events).


  3. In the major area of the Code View, you actually type code. VB already creates two lines of code for you:

    Private Sub controlname_eventname()
       
    End Sub


    All the code for that particular event, must be written between those two lines: in fact the first line tells VB "the code related to controlname's eventname event starts here" and the last line means "code related to the event ends here".
    So, be sure that the cursor is between the two lines and you can start typing code.
To return to the Form View, double-click on the form's name in the Project Explorer, on the right of the screen.

Let's try writing a bit of code: on a new form create a command button, and give it the caption "Click Me!". Now, attach the following code to its Click event:

   MsgBox "Wow! My first working program!"

MsgBox is a Visual Basic command that pops-up a small information box; the text following the command (that must be enclosed into the quotation marks ") is the text that will be shown in the info box.
Your event code should look like the following:

Private Sub Command1_Click()
   MsgBox "Wow! My first working program!"

End Sub

Now, run your program (remember the Run button or the F5 key?) and click on the command button: by doing this, the Click event is triggered and its attched code is executed. The result is shown on the right.

Great uh? That's just the beginning.
Try attaching the above code to various controls: try working with the events Click, MouseMove, Load (Form), KeyPress (Textbox).

Control names

As I said, controls are the interface of the program and code is a sequence of instructions telling the program what to do in response to events. Now I'm going to explain you how to manage controls from code.

When you refer to controls from the code, you use names: a control's name is not its type, but a unique name that identifies it on the form; for example you may have two command buttons with captions "Yes" and "No": we may call them ButtonYes and ButtonNo. When you create a control, an automatic name is assigned to it (such as Command1, Command2, ...).   It is good to immediately replace the automatic name with something more understandable for you.
To change a control's name, change its Name property (from the Properties window).

There is a sort of "naming convention" among VB programmers: it consist in putting a 3-letter prefix at the beginning of a control's name, identifying its type. So, a "Yes" button can be called cmdYes, a label containing information can be called lblInfo, and so on. That's not compulsory, but it helps you a lot remembering the type of control.

Properties and code

Once you have provided each control with a name, you can refer to it from code.
The simplier operation is changing properties from code: while property values set at design time are fixed, using code to change properties you can make controls change dynamically during execution.
To change a control's property from code, use the following syntax:

    controlname.propertyname = newvalue

For example, create a command button with the Caption "Click me" and name cmdClickMe.
Attach the following code to its Click event:

    cmdClickMe.Caption = "You clicked me"

Now, if you run the program and click the button, you will see its caption change.

Have you noticed that all the plain text is enclosed in quotation marks? That's one of VB basic syntax rules. On the contrary, numbers are typed without quotes.

The syntax controlname.propertyname can be used within other VB instructions, such as the MsgBox we've seen before. You can now make a program that shows the text entered in a textbox in a message box. Start with adding two controls to the form: a textbox (txtName) and a command button. Use the following code for the commandbutton's Click event:

    MsgBox "Your name is " & txtName.Text

The above code shows a message box with a message made up of two parts: a first fixed chunk, "Your name is " (enclosed by quotes) and the Text property of the textbox (that contains the text typed); note that this last part is not enclosed by quotes, because you don't want to actually show the text "txtName.Text", but the value of the Text property of txtName. Also note the & operator, used to concatenate two chunks of text.
The final result is shown on the right.

With your current knowledge, you can really create   small programs: you are free to practice yourself with controls, properties, code and events. In the next paragraph, we will face the argument of methods, the last part of controls code that you need to learn.

Methods

You're going to learn the last aspect of controls programming: methods.
A method, as a property, is an element belonging to an object: The difference is that, while properties define characteristics of a control, methods define actions that we can tell a control to take.

For example we can "ask" a picture box to refresh its contents (the Refresh method), a listbox to add a new element (AddItem method), a form to show up (Show method) and so on.
Methods, because of their nature, can't be used at design time, but only from code and at runtime. To fire a method, use the following syntax:

    controlname.methodname [parameters]

The [parameters] are not always needed: it depends on the type of method. For instance, if we tell a picture box to refresh, no more information is needed, but if we want a listbox to add a new element, we must specify its text. To know the available methods for a control and their syntax, the only way is to refer to the Visual Basic Help.

When reading syntaxes of commands, you will often found elements enclosed in square brakets ([]): that is a convention to indicate optional parameters. On the contrary, compulsory parts are typed in italics.

Some examples of methods code:

    pctPhoto.Refresh                     'refresh a picture box
    Form2.Show                           'bring up another form

    lstEmployees.AddItem "John Smith"    'add an element to a listbox

Visual Basic lets you include comments in your code: they are very useful to orient yourself in code.
VB considers a comment everything following an apostophe (
'), and highlights it in green.

Now, let's create a simple program that uses a method. Put a listbox, a textbox and a command button on the form; call them respectively lstNames, txtNewName, cmdAdd. Give cmdAdd the caption "Add name". We want the command button to add the contents of the textbox as a new element in the listbox, and then clear the textbox.
For this purpose, enter the following code in the Click event of the command button:

    lstNames.AddItem txtNewName.Text
    txtNewName.Text = ""

The first line adds the contents of the textbox as a new item in lstNames: note that we used the AddItem method and that we used txtNewName.Text as its parameter. The second line sets the Text property of the textbox to no text, indicated by "".

Use of the standard VB controls

You already used some of the Visual Basic controls: command buttons, textboxes and listboxes. Now, let's briefly sum up the use of all the standard controls.
The following rules apply to every control:

Label
Abbreviation:
lbl
Probably the most simple control: it is used to show text on a form. Use the Caption property to return/set the text displayed in the label. Also the BackColor, ForeColor and Font properties are important to change its appearance.
Textbox
Abbreviation:
txt
Used a lot: allows the user to type information in it. Use the Text property to retrieve the text entered. Again, take a look at the Font property and at the MaxLength property (to impose a limit to text length).
Checkbox
Abbreviation:
chk
It is used to set on/off settings in a program. The main properties are Caption and Value: the latter returns/sets the status of the checkbox, 0 (= unchecked), 1 (= checked).
Option Button
Abbreviation:
opt
With two or more of these controls, you can give the user the ability to choose between multiple options. The Value property returns/sets its state: True (checked), False (unchecked).
List Box
Abbreviation:
lst
This control holds a list of plain text items. To add a new element, you use the AddItem method as follows:

    listbox.AddItem "Item Text"

Each new item is given an increasing index, ranging from 0. The ListIndex property returns/sets the index of the selected item. To remove a item, you use the RemoveItem method, providing it with index number:

    listbox.RemoveItem index

To completely empty a listbox, fire the Clear method, that has not parameters.
To return the text of the selected item, use the Text property. To return the number of item, use the ListCount property.
Other important properties are Sorted (once activated, alphabetically sorts items) and Style (that, if set to 1, puts a checkbox beside each item).

Combo Box
Abbreviation:
cbo
Almost the same of a listbox, the only difference is in appearance: depending on the Style property, you can make it look like a dropdown list (a listbox that pops up when clicked, Style = 2), a simple combo (a normal listbox with a text area you can use to look up elements, Style = 1), a dropdown combo (a dropdown list you can type into like a combo box, Style = 0).
Command Button
Abbreviation:
cmd
The most common Windows control. Used to activate any type of operation: the only very important property is Caption. The code to be executed should be attached to the Click event.
Frame
Abbreviation:
fra
A container control that let's you group other controls together. It is not only used for esthetical purposes: for example, when you create two sets of option buttons on a form, each set should be contained in its own frame.
The most important property is, once again, Caption.
Image
Abbreviation:
img
Great! Decorate your forms with images. Images are loaded using the Picture property. To load a file at runtime, you can use the LoadPicture command:

    image.Picture LoadPicture("file path")

Picture Box
Abbreviation:
pct
This is not a duplicate control: while images only show fixed images (to "decorate" your forms), picture boxes are more advanced and they can contain dynamic graphics. The difference between an Image and a Picture Box, is the same there is between a Label and a Textbox.


Horizzontal and Vertical Scroll Bar
Abbreviation:
hsb, vsb
These controls are used to scroll elements, text and lists across the form. Many controls (such as textboxes, listboxes, comboboxes) have scroll bars "built-in", so you don't need to add them. The use is fairly simple: set the Min and Max properties with minimum and max values; then put code in the Change event (triggered when the scrollbar is used: use the Value property of the scrollbar to refer to the position of the drag-box.
Timer
Abbreviation:
tmr
A tool as little as important: it lets you execute code at regulars interval of time (i.e. every second). To use it, just provide the Interval property with a time in milliseconds (1 s = 1000 ms) and attach the code to the only event available, named Timer. Remember that this control is invisible at runtime.
Drive List Box
Abbreviation:
drv
A little combo box already filled with letters and names for all system drives (floppy, hard disk, CD-ROM, ...). The selected drive letter is stored in the Drive property. The most important event is Change.
Directory List Box
Abbreviation:
dir
This list box shows all the directories contained in a path, and lets the user select any directory or sub-directory. The final selected path is found in the Path property of the control. Again, each time the selected folder changes, the Change event is triggered.
File List Box
Abbreviation:
fil
The 3rd of the file-related group of controls: it shows a listbox filled with all the files located in a specific path. The path to search into is set in the Path property, the name of the selected file in the FileName property. This control is often used in pair with the DirList control to select the path. It also has all the properties/method typical of a ListBox (ListIndex, ListCount, ...).


learnvb30.gif (923 byte)
Line and Shape
Abbreviation:
lin, shp
As you are probably thinking: the first draws a line, the second a circle, square, rectangle, oval, etc. To set the shape drawn by a Shape control, use its Shape property. Both the controls can be colored with the ForeColor, FillColor and FillStyle properties. Neither methods nor events are available for these controls.
Data
Abbreviation:
dat
If you plan to work with databases, you will use this control a lot. It creates a "link" between a database table and other controls (textboxes, listboxes, ...). You first set the path of the DB file in the DatabaseName property and you select a table name from the RecordSource property. Then, you add other controls (for example textboxes) and set their DataSource property to the data control name and their DataField property to the field of the recordset to read/write. At runtime, you use the data control to scroll records and the asssociated controls to read/write fields.
OLE container
Abbreviation:
ole
OLE (Object Linking & Embedding), is a Windows standard that lets applications to "borrow" objects from other applications, such as sound files, Word files, Equation Editor objects and more.

 

Lesson 1

Your feedback/requests about tutorials?
Let me know! Click here.

Lesson 3

Click Here!


Visual Basic Programming Zone is a website by Lorenzo Dalla Vecchia.
To contact the Webmaster, click here.
Hosted by InWind: www.inwind.it