Professional Documents
Culture Documents
Visual Basic is an event-driven language. So, when you talk about events,
we're talking about things that happen in the program which cause little
events to occur (similar idea to IRQ stuff you learned hopefully in 455). An
example of this could be clicking a button causing a button_click event to be
generated. You write code to react to these events and guide a user through
your program.
You design your form completely visually, using a set of widget tools and
drawing on the form directly just like you would in a paint program or
something like this. This stuff is so easy, you'll love it ... or maybe not ... but
it's quick and relatively pain free.
Okay, these examples were developed by James Tam, and I've just
reproduced them here. His website has all his full details on what exactly
these things entail, but I'll get into them a little bit myself. If it seems that
there's something missing here, be sure to check out over there for more
info.
Okay, the first thing you need to do with visual basic is basically just start it
up. No problem. Go:
Start --- Programs --- Microsoft Visual Basic --- You get the picture .... :)
When you load it up for the first time, Microsoft Office might churn away for a
couple of minutes. This is an issue with Office 2000 and you don't need to
worry about it too too much. It will only happen the once. In any case, when
VB is finally loaded up, and you pick Standard Exe from the new project
dialog, here's what you'll be confronted with:
When you click it, you should get the shell for
the Form_MouseMove( ... ) subroutine. Here's the code you want for that
routine:
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As
Single, Y As Single)
lblCoordsB.Caption = "x = " & X & " y = " & Y
End Sub
Now when you run the program, you should get an active record of where
your mouse is when you move it around on the form.
Okay, good to go. One last thing to add to this program. Using the
tool,
draw a checkbox on the form.
Change the (name) property of the checkbox to chkBGColour.
Then, change the caption property of the checkbox to read Change
Background Colour.
Next, double click the checkbox to give yourself a shell for
the chkBGColour_Click() event handler. The code for that routine looks like
this:
Private Sub chkBGColour_Click()
' If CheckBox checked then set background of form to red.
If (chkBGColour.Value = Checked) Then
Form1.BackColor = RGB(255, 0, 0)
' If CheckBox is unchecked then set background of form to grey.
ElseIf (chkBGColour.Value = Unchecked) Then
Form1.BackColor = RGB(210, 210, 210)
End If
End Sub
And that should pretty much do it for the program. If you run it now, it should
do all the same stuff that the example you downloaded did.
back to the top!!
Open and Run the Second Example Program
The second example program is a little more complicated, but not that much.
It just shows you a bit about list boxes and throwing stuff back and forth.
Cool, without further adue, check out the download link:
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
The project file for the
(note: you need to extract both files).
On your desktop, you should now have a folder called second example
program.
"example02"
Go in there and double-click "Example2.vbp" (.vbp stands for "Visual Basic
Project")
Now, you should get VB loaded up with that project, no problem!
With that going, you can push the play button (center of the top tool bar) and
see what it looks like. There are a couple of things you can do with it:
You can add whatever text is typed into the text box as an entry in the
listbox.
You can remove entries from the listbox by pressing the "remove" button.
You know how to change the caption property of the main form, but you don't
need to ...
Okay, I'm going to give this to you really quickly.
Add a button.
change its caption to &Add - note: the '&' will make the letter after it a
keyboard shortcut
change its (name) to cmdAdd
Add another button.
change this second button's caption to &Delete
change that button's (name) to cmdDelete
Add a label.
change the label's caption to Text to add or which ever saucy comment you
like. :)
Add a textbox using the
tool (just draw it on the form like the other
controls!)
change that textbox's (name) to txtAddText
Add a listbox using the
tool (again, just draw it on the form!)
change that listbox's (name) to lstTextList
And that should be it for the Form Design portion of this program. Now we
just have to fill in the code for each of these controls.
Double-click on the form ... but be careful to not double-click on any of your
controls! This should get you the Form_Load() routine. Note: this gets called
automatically every time the form loads up from scratch... Here's the only
code for that:
'if there's nothing in the listbox, disable the delete button...
Private Sub Form_Load()
If (lstTextList.ListCount = 0) Then
cmdDelete.Enabled = False
End If
End Sub
Now, go back to the form design window and double-click the Add button.
The code for cmdAdd_click() is as follows:
Private Sub cmdAdd_Click()
' Add the string that is currently in the textBox to the List Box.
lstTextList.AddItem txtAddText.Text
' delete button disabled? enable it. :)
If (cmdDelete.Enabled = False) Then
cmdDelete.Enabled = True
End If
End Sub
Once that's done, get the form design and double-click the Delete
button. cmdDelete_Click() looks like this:
' This method contains the code for the click event for the delete button.
Private Sub cmdDelete_Click()
' if the listbox isn't empty, remove an item ... disable delete button if
necessary...
If (Not (lstTextList.ListCount = 0)) Then
lstTextList.RemoveItem (lstTextList.ListCount - 1)
If (lstTextList.ListCount = 0) Then
cmdDelete.Enabled = False
End If
End If
End Sub
And we are done! If you run the program now, you should be able to add and
remove stuff from the listbox depending on what you type in the textbox.
Fun, eh? :)
back to the top!!
MSDN Visual Basic Documentation
The MSDN Library is available from a few different locations and contains
a ton of information about Visual Basic and other Microsoft Visual Studio
stuff. (I'm not pluggin' it, I'm just saying it's useful if you're using the
products. :) ) Anyways, here's some ways to get at it:
In the Start menu, it's under Microsoft Developer Network
In VB, just go to the help menu and hit Index
In a web browser, you can go to the MSDN online site (that has lots of
technical articles and other stuff). Their website
is http://msdn.microsoft.com/. This is the only resource that you can get at
from anywhere... ie, you can load the library browser from home unless you
have the disks. :)
Yeah. :) That's where you get it. If you load the program from VB or the start
menu, this is what your browser looks like:
filter down what you're looking at by changing the active subset that MSDN's
looking at to just look at Visual Basic. It's as easy as picking the Visual Basic
subset from the dropdown list (see the picture, below)!! (damn that sounded
cheesey, I should be in marketing...) In any case, now stuff that's specific to
VB is black text in the index list and unrelated stuff is sorta greyed out.
Select the rows in the design view (as pictured above) that
have ArtistName and AlbumTitle
Right-click on that selection, and pick Primary Key from the menu you get.
This will make both fields into primary keys. The idea is that they can be
primary because you'll never have identical artist names and album titles
(otherwise what's the point?!).
Once you've got your table built, just close that window. You'll be
automatically prompted to save changes to the table design and to give the
table a name. I picked CDs, how original. :)
Once that's all done, you can either add a couple entries to the database by
double clicking the CDs table from the database design main window and
inputting them manually or just move on to:
Export the database to Access '97 (this is the annoying part of the whole
thing) Here's what you do:
Go to the Tools menu
Select Database Utilities
Select Convert Database
Select To Prior Access Database Version
You'll get a save file dialog that will let you enter a name for your database. (I
used "CDCollection.mdb") Just save it in the same folder as your Access 2000
version of the file. Whatever you call it, make sure you keep track of which
database file is which version!!
End With
Data1.Refresh
'clear the text fields once the new record is added
txtArtistName = ""
txtAlbumTitle = ""
txtTrackCount = ""
End Sub
Last thing you need is the remove code. In the form design window, doubleclick the Remove Selected button. You should get a shell for
the cmdRemoveEntry_Click() subroutine. This is the code:
Private Sub cmdRemoveEntry_Click()
'delete an entry from the database
With Data1.Recordset
.Move (MSFlexGrid1.Row - 1) ' we minus one because row zero is the
header row
.Delete
End With
Data1.Refresh
'set the focus back to the first add field
txtArtistName.SetFocus
End Sub
And we are done! It's actually pretty simple to do this stuff, no problem!!
Before you run this thing, you will need to save the project to the same folder
that you saved your database file from the above section to.
back to the top!!
Download and Run Example Program 4
Example programs 4 and 5 were both written by Saul and have the basic
goal of teaching some more about event handling in VB as well as teaching a
little bit about how to go about using a canvas-style widget. Without further
adue, let's check out the first simple example:
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
The project file for the
(note: you need to extract both files).
On your desktop, you should now have a folder called simple sketchpad
program
"Sketchpad1"
From the dropdown list on the top of the code window, pick
the MouseDown event. Here's the code to fill that one in:
'Set the first point and start the line
Private Sub picCanvas_MouseDown(Button As Integer, Shift As Integer, X As
Single, Y As Single)
If Button = 1 Then
picCanvas.Line (X, Y)-(X, Y)
End If
End Sub
Once that's filled in, from the same event drop-down list at the top of the
code window, pick the MouseMove event. The code for that bad boy is right
here for the taking:
'Continue the line to the next point as we move the mouse
Private Sub picCanvas_MouseMove(Button As Integer, Shift As Integer, X As
Single, Y As Single)
If Button = 1 Then
picCanvas.Line -(X, Y)
End If
End Sub
That should be it! This is pretty simple, all it does is listen for a button click
with the left mouse button on the picturebox. If it gets a mousedown
followed by a drag, it draws a blue line (as was set up in the form_load
subroutine). Simple use of events makes a fun little app!!
back to the top!!
Download and Run Example Program 5
Example program 5 (also written by Saul) is an extention of the idea
presented by Example program 4. It has the same basic concept with a ton
of more features! I won't go through how to build it here, but leave it to you
to download this sucker and play around with it, because you can do some
pretty neat things pretty easily.
Fun challenge: try to implement a feature that would let you save whatever
you draw in the canvas to a bitmap or jpg file!
Click here to
download
Okay, the steps to follow:
Just save the file to your desktop.
Double click the file to open it with winzip.
Click "Extract" and extract the file to your desktop
The project file for the
(note: you need to extract both files).
On your desktop, you should now have a folder called extended sketchpad
program
"Sketchpad2"
There's not too much you can do with the form at this time. Basically, you
adjust the BackColor and the StartUpPosition(where it will open on the screen
when you Run it) and then you start putting controls on it.
The Label
This is probably the first control you will master. It is used to display static
text, titles and screen output from operations. The important properties to
remember:
Caption - the text that is displayed in the label
BackColor and ForeColor - colors of the background and the text
BackStyle - Opaque or Transparent - whether the background is visible or not
Font - font and size of text
Alignment - text centered, left or right
Multiline- True or False - if True, you can have several lines of text, delimited
by <CR> in the label - by default, it is set to False
Top
Hopefully, you have now run this program several times, each time you
added a new control, in fact. Admittedly, nothing much happened except to
confirm that the controls were appearing in the right place on the form.
Here now is an example of the code we could write to perform simple tasks:
input name and city and display the information in a label when the Continue
button is clicked. The Exit button will end execution of the program and the
Cancel button (or the Esc key) will clear the fields.
A few explanations: the Form_Load event occurs when the form first opens.
This is where we initialize things - we want the TextBoxes and the result Label
to be empty when we start off so, we set them to a blank space.
The actual processing is done after the data have been entered and we hit
the Continue button. The processing logic is put in the
Continue_button_clicked event.
When you hit the <Esc> key or you click on the Cancel button, you want to
annul the entry you're doing and start over again. That's the same as
opening the form so, we just tell the program to execute the Form_Load
procedure which we already have.
The Exit button uses the pronoun Me to Unload. Me means the form currently
active without having to name it.
Top
Multiple forms
For the next series of examples we will use a new
Form. It is not necessary to create a new Project; any
Project can have several Forms in it.
With the Project open on the current Form, go to:
Menu --> Project --> Add form. Select New form in the
creation window and, voila! Next time you save the
Project, it will ask you to name this new Form. You can
name it Lesson4B.frm for example.
One more detail: when you Run the Project, you want
to tell it which Form to open.
Go to the Project Manager window, right click on the
Project name and select Project properties. In the
Project properties window, the ListBox on the right
says "Startup object". Select the Form you want to
open when you Run. You can change the Startup
object at any time to run the different forms that you
created.
Check boxes & Option buttons
These two controls are used when the user must choose from a list of
options. The difference between the two is that with Check boxes he can
select several at one time but, with Option buttons, he must select only one
among several.
The example below illustrates the use of Check boxes and Option buttons. To
capture the information entered by means of these controls, you must test
the property: Value. In a Check box, Value = 1 if box is checked and = 0 if
not. In an Option button, Value = True if selected and = False if not.
The code, although somewhat long, is not very complicated. Most of the
time, processing consists of checking the content of .Value. It is fairly
standard procedure, especially with Option buttons, to ensure that at least
one button has been selected and to display an error message if it has not.
Assignment 3
Create the Payroll form shown below. Number of hours must be entered as
well as the appropriate rate. Gross salary = rate * hours. Net salary = gross
salary - deductions.
You will note that the Editor has all the functions of a text editor and then
some. The most commonly used functions will be Cut ... Copy ... Paste which
you can call from the Menu, from the Toolbar or from the right mouse button.
You also have access to the usual Find andReplace functions ....
Getting help
There is a lot of documentation available on VB. There is so much, in fact,
that it's easy to get lost in it. However, the on-line Help available from the
Menu should be used regularly. Very often just doing a search on a word in
particular will be sufficient to get you out of a jam. If you want to go into
more detail check out the Contents part of MSDN (Microsoft Developers'
Network) and surf through it.
Writing code
VB is not very particular about presentation - spaces, indents, lower case or
upper case, it doesn't make too much difference to the compiler. But it may
make a whole lot of difference to the programmer who has to maintain your
code in 2 years, after you've moved up to being CEO of the company.
Apply "Best Programming Practices"
When you work with RAD (Rapid Application Development)
tools like VB in a graphical interface environment, you
become more than just a programmer, a writer of code. You
are a developer. We will cover that in the next lesson.
But at the moment, you are still a Programmer. And unless
you are developing an application for your own personal use,
that nobody else will see, you have to think of the
environment, of the team you are working with.
"No man (or woman) is an island!"
Especially when it comes to programming. The code you
write may have to be checked by an Analyst. It will have to
go through testing. It may have to be modified by other team
members and it almost certainly will go through
Naming conventions
These are the rules to follow when naming elements in VB - variables,
constants, controls, procedures, and so on:
A name must begin with a letter.
May be as much as 255 characters long (but don't forget that somedy has to
type the stuff!).
Must not contain a space or an embedded period or type-declaration
characters used to specify a data type ; these are ! # % $ & @
Must not be a reserved word (that is part of the code, like Option, for
example).
The dash, although legal, should be avoided because it may be confused
with the minus sign. Instead of Family-name use Family_name or
FamilyName.
Data types
Data type
Storage
Range
size
Byte
1 byte
0 to 255
Boolean
2 bytes
True or False
Integer
2 bytes
-32,768 to 32,767
Long (long
integer)
4 bytes
-2,147,483,648 to 2,147,483,647
Single
(singleprecision
floatingpoint)
4 bytes
Double
(doubleprecision
floatingpoint)
8 bytes
Currency
(scaled
integer)
8 bytes
-922,337,203,685,477.5808 to
922,337,203,685,477.5807
Decimal
Date
8 bytes
Object
4 bytes
String
(variablelength)
10 bytes
+ string 0 to approximately 2 billion
length
characters) + string
length
User-defined Number
(using Type) required The range of each element is the same as the range
by
of its data type.
elements
In all probability, in 90% of your applications you will use at most six types:
String, Integer, Long, Single, Boolean and Date. The Variant type is often
used automatically when type is not important. A Variant-type field can
contain text or numbers, depending on the data that is actually entered. It is
flexible but it is not very efficient in terms of storage.
Top
Declaring variables
Declaring a variable means giving it a name, a data type and sometimes an
initial value. The declaration can be explicit or implicit.
An explicit declaration: variable is declared in the Declarations Section or at
the beginning of a Procedure. An explicit declaration looks like:
Dim MyNumber As Integer
Now the variable MyNumber exists and a 2-byte space has been reserved for
it.
An implicit declaration: the variable is declared "on the fly", its data type is
deduced from other variables. For example:
Dim Total1 As Integer
'Explicit declaration
Dim Total2 As Integer
'Explicit declaration
Total3 = Total1 + Total2
'Implicit declaration
Total3 is not formally declared but is implied, it is "arrived at" from the other
declarations.
It is never a good idea to have implicit declarations. It goes against the rules
for clarity, readability and ease of use of the code.
To make sure that this rule is followed, start the Declarations with the Option
Explicit clause. This tells the compiler to consider implicit declarations as
errors and forces the programmer to declare everything explicitly.
Other examples of declarations:
Dim MyName As String
Dim StudentDOB As Date
Dim Amount5, Amount6, Amount7
In the last example the type assigned to each variable will be: Variant. It is
Exponent (power
4^2
of)
16
Multiply
5*4
20
Divide
20 / 4
Add
3+4
Subtract
7-3
Mod
Remainder of
division
20 Mod 6
Integer division
20 \ 6
&
String
concatenation
"Joan
Smith"
Equal to
9 = 11
>
True
<
Less than
False
11 < 9
False
>=
Greater or
equal
<=
True
<>
Not equal
9 <> 9
False
AND
Logical AND
(9 = 9) AND (7
False
= 6)
OR
Logical OR
(9 = 9) OR (7 =
True
6)
15 >= 15
True
Top
Control Structures
If...Then...Else
If condition1 Then
statements1
Else
statements2
End If
If condition1 is True, then statements1 block is executed; Else, condition1 is
not True, therefore statements2 block gets executed. The structure must be
terminated with the End If statement.
The Else clause is optional. In a simple comparison, statements1 get
executed or not.
If condition1 Then
statements1
End If
Select Case
Can be used as an alternative to the If...Then...Else structure, especially
when many comparisons are involved.
Select Case ShirtSize
Case 1
SizeName.Caption = "Small"
Case 2
SizeName.Caption = "Medium"
Case 3
SizeName.Caption = "Large"
Case 4
SizeName.Caption = "Extra Large"
Case Else
SizeName.Caption = "Unknown size"
End Select
Do...Loop
Used to execute a block of statements an unspecified number of times.
Do While condition
statements
Loop
First, the condition is tested; if condition is True, then the statements are
executed. When it gets to the Loop it goes back to the Do and tests condition
again. If condition is False on the first pass, the statements are never
executed.
For...Next
When the number of iterations of the loop is known, it is better to use the
For...Next rather than the Do...Loop.
For counter = start To end
statements
Next
1) The counter is set to the value of start.
2) Counter is checked to see if it is greater than end; if yes, control passes to
the statement after the Next; if not the statements are executed.
3)At Next, counter is incremented and goes back to step 2).
More will be covered on Control strucures as it becomes necessary in
upcoming lessons. Meanwhile,if you want to know more, consult the VB
Language Reference.