Visual Basic Concepts and Keywords                                  

   Visual Basic
   Style Sheets
   Active X
   TDC Binding
   Perl and CGI


Visual Basic 6 is considered an object-oriented,  high level language.   "High-level" signifies not that it is more powerful than C++, but that it is closer to pseudo code or plain English in its usage.  It is not as powerful, fast or efficient as C++.  Nor does it give the programmer the control over memory management with pointers and references that C++ does.  That's o.k., because none of these features are Visual Basic's claim to fame.  Visual Basic's key advantage is its ease of use.  This greatly reduces the amount of time needed to develop an application, since it
provides so many encapsulated methods, functions and attributes to its visual class objects.  Visual Basic applications can be developed and deployed more quickly than C++ and MFC projects.   Note that,
when distributing VB 6.0 applications, you can include the VB 6 runtime file (.dll) - msvbvm60.dll .  It is located in the  C:\WINNT\System folder (or a similar path).  Microsoft allows freely distributing this file with your applications.  If you need it to run the examples, download it here:  msvbvm60.exe

Robin: "Holy smoke, Batman, it looks like Microsoft included a few surprises!" 
Batman: "Yes, hold on to your tights, old chum.   Just as I suspected, as an added bonus, Microsoft threw in a HTML editor in VB 6 that enables you to use the tool bar to add text boxes and check boxes - a clever twist of fate!"

We have to have some fun, now don't we?  So back to the topic at hand:

If you know C++, you will notice right away that the object structure in VB conforms to the class structure of C++.  Like C++ classes, every VB object has its own instance,  data members and methods.  Use the right tool for the job - If you have the time,  use C++ for efficiency and powerful capabilities.  If you don't have much time and don't truly need precise efficiency, use Visual Basic.  Each contrasting development language is useful when applied to its appropriate task.   All OOP languages generally follow the same OOP philosophy, though they differ
according to how they meet OOP needs and implement OOP structure.

Fundamental Theory of Object Oriented Programming

Object Oriented vs. Procedural Languages - Object-oriented languages (VB, Java, C++) are set apart from procedural languages (C, Fortran) primarily by their employment of classes and class-like structures, which provide "encapsulation".  Procedural languages would use functions in a more linear fashion. Object oriented languages attempt to emulate real world systems and structures more closely than procedural programming.  In the past computers weren't as powerful and memory was very expensive.  As a result programs were largely console or command prompt based (i.e. DOS, Unix without X Windows). Software was written in a linear and procedural manner, to optimize efficiency when running on slow processors and to squeeze every available iota of usefulness out of limited, paltry and expensive amounts of memory.  Rich multimedia, power
and vast capabilities weren't as important as simply coding something that could run on a bare minimum of hardware.

Today, priorities have shifted.  Powerful CPUs and ample memory are abundant and cheap, and the real expense in software development is in
the amount of time it takes to develop an application.  This revolution is due to Moore's Law, which states that CPU speeds double every 18 months.  As a result, CPUs become faster and cheaper.  One can see the trend in a brief history of computing technology.  It is this revolution in hardware that has made the revolution in high-level languages like VB possible.   In addition, this has brought us into the realm of generating complex decision structures that can analyze data and user input, known as AI algorithms.  While procedural languages made heavy use of the command console and linear input, object-oriented programs, because of their heightened modularity, lend themselves more completely to event-driven input from the user. 

Encapsulation - Encapsulation boils down to doing one well-defined thing completely.  C++ and VB encapsulate code using self-contained CLASSES.  Class structures build components that have known generalized properties.  To represent a cat in C++, you would build a Mammal class.  All mammals in the real world have certain traits in common:  they may be hairy, warm-blooded, or possess appendages.  They also possess certain methods or perform similar functions: they each sleep, eat, reproduce and die.  Therefore, mammal would be a good base class.  We could create a Cat class that inherits from the Mammal class, and so could use all of the mammal class's  data members and methods, as well as special methods and data members particular only to cats:  (i.e. the "void Meow()" function or the "bool Purr" attribute.   Again, the trend is to break down the complexity of large programming tasks by making code modular ( like
L-E-G-O-s ).  Encapsulated code is code that can be plugged into a program and modified as needed.  Encapsulating means treating data and procedures that act upon the data as a single "object" - a self-contained entity with an identity and certain characteristics of its own.  Think of LEGOs, and you can't go wrong!  :)

Data Hiding - The inner workings of classes should be hidden. The prevailing philosophy for developing complex software is that you don't need to know how classes and precompiled code work, simply how to use them.  This enables large projects to be divided up among teams of programmers, where each programmer can develop a portion of the project that is modular and largely independent of the other parts of the program.  At the close of the project, teams and programmers can link their modularized objects together in LEGO-like fashion to produce an application that is greater than the sum of its parts   This enables adding complex functions and routines to code without having to "re-invent the wheel", so to speak.  It allows each programmer to build upon the work of his predecessor, as well as leave a lasting legacy for those who come after her/him.  Let's sum this up again:

Encapsulation speeds up development time through the use of encapsulated libraries of code, functions and classes that each perform a specific task and snap together in a "Lego" fashion. They are then used in constructing larger and more complex bodies of code that incorporate these functions and the whole becomes more than the sum of its parts. Data Hiding provides greater security and flexibility by making it possible to examine relevant portions of source code without seeing the source in its entirety.  You can use classes, libraries and modules without having to understand how they work or reinvent them.

Inheritance - Reuse, reuse, reuse!  Don't reinvent the wheel.   A new type can be declared as an extension of an old type, a sub class of an existing class, or derived types and classes from base classes.  The idea is to follow as closely as possible the model of a real world object.  Each real world object has both a "has a" and an "is a" relationship.  Class objects and code modules should follow this.

Polymorphism - Different objects do the right thing through function polymorphism and object polymorphism. Polymorphism refers to the same name taking many forms.  In other words, multiple inheritance.  Classes can both inherit from base classes and be the foundation of other classes themselves.  While not truly supported in VB6, provision is made in VB.NET for polymorphic functionality.

The Visual Components of the User Interface
All of the controls in Visual Basic are added to a form by clicking on a control item in the toolbar and then clicking on a form object to create an instance of that object.  Basically, by selecting and clicking you are creating an object.  Thinking of this in terms of instantiation will assist those familiar with the MFC.  

Some of the visual form elements and some of their attributes are:


These items are set up by default to respond to "event handlers".

Event Handlers - respond by default when a the user performs an action on a VB form object (i.e. Clicking, Changing, Dragging, Dropping, MouseOver, etc.).

Some Common VB Event Handlers


Option Explicit - forces all variables to be declared before they are used.

Combining objects. Use the + or the &.  If the data types are identical you can use +.  Example:
apples = "apples and"
oranges = "oranges"
fruitsalad = apples + oranges
If the data types are different use &.  Example:
fruitsalad = oranges & 42  (Yes, I'm a big Douglass Adams fan - Hitchhiker's Guide to the Universe.  42 = Answer to Life, the Universe and Everything.)

variable - a container of memory into which you can place values using the assignment operator
assignment operator - looks like "equals", but really says take what's on the right and store  it in the variable on the left.

You may declare variables before assigning values to them, in which case you may specify a data type.
- stands for "dimension", used in variable and array declaration.  A variable is a container/unit of memory to hold values.  Examples:
Declares a variable - Dim variable1
Declares Multiple Variables - Dim variable1, variable2, variable3
Declares and Sets Data Type of Variable - Dim variable1 As String
Declares an Array with 5 Elements - Dim SomeArray(1 To 5) As Integer
Declares a Multi-dimensional Array  - Dim SomeArray(8,8) As Integer

Data Types
Data types are, simply stated, different types of data.  Computers store memory through manipulating millions of molecular-sized switches sandwiched between negative and positive layers of silicon.  By turning these switches on and off, any type of data can be represented and stored.  Computers do this by converting everything to binary, or Base 2.  Base 2 represents everything in powers of 2.  There are only 2 values for a computer,  on or off, 1 or 0. So if something can be converted to Base 2, it can be stored in memory.  We humans are more familiar with base 10 - that is powers of 10:

104       103 102  101   100
10,000 1,000 100 10 1

110 =  1 1 0
5 =  0 5
10 =  1 0
11 =  1 1

So in Base 10,  a 10 is a "1" in the tens place and a "0" in the ones place.  An 11 would be a "1" in the tens place and a "1" in the ones place.

Base 2 represents everything in powers of 2:

27 26 25 24 23 22 21 20
128 64 32 16 8 4 2 1

255 =  1 1 1 1 1 1 1 1
69 =  0 1 0 0 0 1 0 1
42 =  0 0 1 0 1 0 1 0

These 8 positions of the powers of 2, or bits, can represent numbers from 0 to 255 as switches are turned on and off in their place values.
ASCII characters are represented by these Base 2 values.  Strings are arrays of ASCII characters.

Data types are important because different types of data - integer, single, or string - require different amounts of memory (on/off switches).

To build an application in Visual Basic, one starts with the user interface.  This is the visual form component of the program.  The place where the user interacts with the code.  After the interface phase, we begin to add the code that will govern the behavior of our Visual Basic program.

There are really only a few basic keywords and tools that you will need to code a wide variety of behaviors in Visual Basic.  These structures conform to similar structures in object-oriented languages such as C++ and Java.  The benefit is that, as you learn other object-oriented languages, you will be able to build upon what you know and this will drastically shorten the learning curve.  Let's look at some of these basic structures.

Decision Structures
Used to make decisions, they process logic statements.

If/Then/Else/End If - Evaluates an expression as true or false, then executes the code following depending on the result.  Examples:

    Dim SomeKindOfVariable As Integer
    SomeKindOfVariable = 3

    If SomeKindOfVariable = 3 Then
        SomeLabel.Caption = "All is as it should be."
        SomeLabel.Caption = "Something is wrong."
   End If

Select Case / Case / End Select - Also evaluates an expression, useful for parsing multiple input patterns. Example:

   Dim seriouspain
   seriouspain = Int((6 - 1 + 1) * Rnd + 1)
   Select Case (seriouspain)
               case 1
               response.write("Merely a flesh wound")
               response.write("A mild scrape.")
               case 3
               response.write("You receive a deep cut.") 
               case 4
               response.write("You are bleeding profusely.")
               case 5
               response.write("You are critically wounded.")
               case else
               response.write("You are dead!")
    End Select

Repetition Structures

Used to perform repetitive processing tasks through iteration.
For / Next - When you know exactly how many times you want to loop.  Example:

x = 1 To 10 Step 1
      Label1.Caption = Label1.Caption & x
Next x

Do While / Loop - PREtest loop.  Since test evaluated first, if conditions are not met loop may never be performed. Example:

CounterThingie As Integer
Dim x As String
x = ", "
CounterThingie = 1
Do While CounterThingie < 5
     Label1.Caption = Label1.Caption & CounterThingie &
     CounterThingie = CounterThingie + 1

Do / Loop Until - POSTtest loop.  Since test evaluated after execution, will always execute at least once even if conditions are not met.  Example:

Dim CounterThingie As Integer
Dim x As String
x = ", "
CounterThingie = 1
     Label1.Caption = Label1.Caption & CounterThingie & x
     CounterThingie = CounterThingie + 1
Loop Until CounterThingie > 5

Arrays are like variables that contain other variable inside them.  The components inside an array that can hold values are referred to as "elements".  Arrays can be of one or many dimensions.  You will recognize them by the (# of elements) inside parentheses.   Example:

Dim SingleDimensionArray(1 To 10) As String
SingleDimensionArray(1) = "Charles Germany"
SingleDimensionArray(2) = "Barbara Germany"

'Ahh - The Family Unit :)
Dim MultiDimensionalArray(10,3) As String
MultiDimensionalArray(1,1) = "Charles Germany" 
MultiDimensionalArray(1,2) = "Barbara Germany" 
MultiDimensionalArray(1,3) = "Jacob Germany" 

Arrays are very useful with loops.  Example:

Dim ArrayOfNumbers(1 To 100) As Integer
For x = 1 To 100 Step 1
ArrayOfNumbers(x) = x + 1
Next x

You get the idea, this would save writing 100 lines of code, and that's a good thing!  Yay!  :)  This also makes things easy to search for:

Dim NumberToSearchFor As Integer
NumberToSearchFor = Val(InputBox("Enter number to search for:", "Search for Number"))
For x = 1 To 100 Step 1
      If ArrayOfNumbers(x) = NumberToSearchFor Then
         Label1.Caption = "I found it!  I found it!"         
      End If
Next x

Representing Checkers With a Two Dimensional Array:
             0               1            2           3           4           5           6           6
        5   EMPTY   RED   EMPTY   RED   EMPTY   RED   EMPTY   RED  
        6    RED   EMPTY   RED   EMPTY   RED   EMPTY   RED   EMPTY
        7   EMPTY   RED   EMPTY   RED   EMPTY   RED   EMPTY   RED  

Dim CheckBoard(1 To 8, 1 To 8) As Integer        or        Dim checkerBoard(8,8) As Integer

Tables of Data in Multi-Dimensional Arrays - Create a table with 3 fields and room for 4 records.  Each of the first element has 3 elements itself.  We could use these to store 4 employee's names, socials, and pay rates.    Example:

Dim EmployeeData(4,3) As String
For x = 1 To 4 Step 1     
      For y = 1 To 3 Step 1
            EmployeeData(x,y) = InputBox("Enter data item " & y & " for employee " & x & ".", "Employee Data") 
      Next y
Next x

Scope refers to the availability of an object.  In VB there are three kinds of scope:  minty fresh peppermint, cinnamon, and cherry flavored.  No, I'm just kidding.  The three levels of scope are, in order of globalization:

1 - Global  (Declared in a code module, can be accessed anywhere in program.)
2 - Form Level  (Can be accessed on on form in which declared.)
3 - Local  (Can only be accessed in function or subroutine in which they are declared.)

Try to keep things local as much as possible.  Heaven forbid you should  Pollute your global namespace!  Ahhh . . . . .
Still there will be times when you need globals to pass back and forth between forms.

Subroutines are a way of modularizing (i.e. encapsulating - if you want the extra credit say "LEGOS" 'cause you know I like them) your code.  There are two distinct parts in dealing with subroutines.  You must first DEFINE them.  Like creating a blueprint, defining a subroutine doesn't make it do anything.  The second part, CALLING a subroutine, reads the blueprint and brings the subroutine into action.  Subroutines can take arguments/parameters inside parentheses as a way to pass values from where the routine is being called to where it is defined.  Unlike functions, subroutines can not return a value.  In summary, this is a 2 step process.  Create (define) the subroutine, then call it into action when needed.   Example:

Step 1 - Defining the Subroutine and Accepting an Argument:
Private Sub MySubroutine_Click(PersonsName As Integer)
   Label1.Caption = "Inside subroutine.  Your name is " & PersonsName & "."
End Sub

Step 2 - Calling the Subroutine and Passing In an Argument:

Call MySubroutine("Charles Germany")

Functions are a way of modularizing (i.e. encapsulating - again LEGO mania baby!) your code.  There are two distinct parts in dealing with functions.  You must first DEFINE/DECLARE the function.  This is just the blueprint.  At this point,  the function will not do anything.   The second part involves INVOKING the function.  Invoking it will cause it to become active and process whatever code is inside of it.  Functions can take arguments/parameters inside parentheses as a way to pass values from where the function is being invoked to where it is defined.  Unlike subroutines, functions can also return a value.  If you design your function to return a value, make sure you have a variable ready to catch that value when the function ends.  Using the function's name and assigning a value to it will return that value from the function when it ends, providing it meets the return type you specify in the function header.  So to return the value, instead of using the keyword "return" as it is used in so many other languages, simply type the function's name at the end of the function and assign a value to it.  So for each function, we would : 1-Declare/Define it, and 2-Invoke it.  Example:

Step 1 - Defining the Function that Returns a Value:
Private Function MyFunction(PersonsName As Name) As String
          Dim StringToReturnFromFunction
          StringToReturnFromFunction = "Inside function.  Your name is " & PersonsName & "."
          MyFunction = StringToReturnFromFunction
End Function

Step 2 - Invoking the Function that Returns a Value:
'Note: Create a variable of the same return type to catch the value returned
StringToCatchReturnValue As String
StringToCatchReturnValue = MyFunction("Charles Germany")
Label1.Caption = StringToCatchReturnValue

Sequential Access Files:

Reading From a Sequential File:
Open "D:\CharlesGermany\Apocalyptic\highscores.txt" For Input As #2
Do While Not EOF(2)
      Input #2, HiName, HiScore

Writing to a Sequential File:
Open "D:\CharlesGermany\Apocalyptic\highscores.txt" For Input As #2
Write #1,    'Write a blank line
Write #1, Apocalyptic.lblPlayerName.Caption, Apocalyptic.lblScore.Caption
Close #1

Optionally, instead of using the absolute path, you can pass a relative path to Open using the App.Path functoin in VB.  It works like the Server.MapPath function in ASP scripts, and returns the location the application is currently running in.

A sequential access data file is similar to a cassette tape in that each record in the file, like each song on a cassette, is both stored and retrieved in sequential order.  Access time is related to position in the file.  Sequential files are easy to create, but their drawback is that records must be processed in storage order.  They are most suited to processing a small file, a text file, or a file that will only be accessed sequentially.

Sequential files are opened using the Open statement, as in:      Open pathname For mode As # filenumber

The component, "pathname",  is the filename, including its drive and path, and should be enclosed in quotes (unless it is stored in a string variable). Mode can either be Input, Output, or Append.  For Input files, VB will open the file or issue an error if the file does not exist.  For Output, VB will open a new file or erase the contents of an existing file with the same name.  For Append, VB will open the file and allow you to add records to the end.  An error message will be issued if the file does not exist.  Filenumber is an integer between 1 and 511 that will be associated with the file as long as it is still open.   VB uses a record pointer to keep track of the next record.  For an Input file, the pointer is initially positioned before the first record.  For Output, the pointer is positioned at the beginning of the file.  For Append, the pointer is positioned immediately after the last record.

You can write to a sequential access file, as in:               Write # filenumber, outputlist

"Filenumber" is the file number from the Open statement
and "outputlist"  is one or more numeric or string expressions, separated by commas

Close a sequential file using the syntax:     Close # filenumber

When reading from a file, you can use the EOF(filenumber)  function, which returns true after the last record has been input. 
It is typically used in the context of a While loop,
 so assuming the file number is 1:    Do While Not EOF(1)    Or   Do Until EOF(1)  

You can read from a sequential file using the following syntax: Input #filenumber, variableist

Where "Filenumber" is the file number from the Open statement   "Variablelist" is a list of one or more string or numeric variables, separated by commas.  The variablelist should correspond in number and data type with the data stored in each record of the file. The Print method can be used to output data on a form.  You can print to a printer using the syntax: Printer.Print outputlist

The component,  "outputlist",  is a list of expressions to be output.  The expressions can be separated by commas or semicolons.  A comma forces the output to the next tab position, while a semicolon advances to the next print position.  VB prints positive numbers with a leading and a trailing space.  Negative numbers print with a leading minus sign and a trailing space.  The Spc and Tab functions can help space the output (note: use the semicolon, not the comma with these functions).  Use the Format and RSet statements to right-justify and align numbers by the decimal point.

Random Access Files

A field is a single item of information about a person, place, or thing.  A record is a collection of related fields that contains all the necessary information about a specific person, place, or thing.  A file is a collection of records.  VB supports three types of data files: sequential access, random access, and binary access.  Tutorial 6 covered sequential access; this Tutorial covers Random access; Appendix C covers binary access files.

Sequential access files are similar to cassette tapes in that each record must be read and written in sequence.  Therefore, access time depends on the location of the record in the file.  Random access files are set up like CDs in that each record can be read or written in any order (randomly).  Each record has a unique number, called its record number that indicates its position in the file.  Records in a sequential access file can be variable length, but records in a random access file are fixed length.  Random access files are also called direct access.

You can view the contents of a sequential file using a text editor.  Each record appears on a separate line because VB appends a carriage return to the end of each record.  The contents of the record are in human-readable form.  By contrast, random access files are stored in binary, with no field separators or line breaks.  The number of characters in each field (and therefore in each record) is identical.  So if information is written that does not fill up a field in a random access file, spaces will be written for the remaining field length.  If information exceeds the field length, it will be truncated.  Random access records can be retrieved much faster because of these constraints.

Before you can create a random access file, you must first use the Type statement to declare the record structure, i.e., the names, data types, and lengths of each field in the record.  Place the Type statement in the General declarations section of a code module.  The data types must either be VB standard types or any type previously defined in a Type statement.  Note that the lengths of each type are known, except for the String type, which must be explicitly given a length.  Once defined, the record structure is called a user-defined data type.  If you are a Hungarian notation freak, use the prefix "udt" when declaring variables of a user-defined type, as in:    Dim udtItemRec As ItemStruc

Use the Open statement to open a random access file:    Open myFilename For random As #1 Len = Len(udtItemRec)

This opens a file called “myFilename” for random access read or write.  The file is associated with the #1. 
Its record length is assigned to Len via the Len() function which measures the length in bytes of the data type supplied to it.

The Close statement is simply:   Close #filenumber

To write to the file, use Put:   Put #filenumber, [recordnumber], variablename

Note that random access files might contain garbage and should be initialized before any records are written to them.  To initialize the file, 
write spaces to the string fields and 0’s to the numeric fields.  Remember to  prompt the user to verify that they want you to initialize the file, 
since they will loose all data in any existing file they initialize.  

To read from a random access file, use Get: 
   Get #filenumber, recordnumber, variablename

The component "filenumber",  is the number used in the Open statement to open the file.  "Recordnumber" is the number of the record to be input.  Variablename is the name of the variable to hold the data from the file.

Object Variables

An object variable is similar to any variable except it holds a reference to an object rather than the data contained in an object.  After creating an object variable you can use the Set statement to assign an object reference to the object variable.  Once the reference is made, the reference variable can be used (usually a shorter name).  Example:  

SomeVariableName As Object
SomeVariableName = NameOfObjectToReference 

You an pass object variable by reference from one subroutine or functoin to another:  Example:

Round function - returns a number rounded to a specific number of decimal places.  Example: Round(expression, numberdecimalplaces)

the term "expression" is a numeric expression and numberdecimalplaces is the desired number of digits to the right of the decimal point.
If this is omitted, the Round function returns an integer.

Passing By Value vs. Passing By Reference:

By default in VB 6, all values are passed by reference.  Passing by reference means the memory address of the actual variable is passed in to the function, subroutine or class method.  In this way, changes made to the variable are global by default.  This is more efficient in terms of memory, yet less secure.  There are times when you want to manipulate a value passed in as an argument or parameter to a function, and yet you only need a copy - you don't want to change the original variable.  You will then need to pass by value instead of reference.  The keywords "ByVal" and "ByRef" can be used to determine how a variable is passed. Example:

Passing by value:   Public Function PlayASound(ByVal SoundName As String, ByVal Loop As Boolean) As Boolean
Passing by reference:   Public Function PlayASound(ByRef SoundName As String, ByRef Loop As Boolean) As Boolean

Classes in Visual Basic:

'C. Germany - 2003.  Example Monster Class.  In comments are the class tags where class declaration
'Would normally be. The steps for adding classes are as follows:
'1. CLick -> Prokject -> Add Class Module.  Create Your Class.
'2. Define your variables (data members) as private in general declarations section of module.
'3. Add accessor methods (Get and Let)
'4. Define/Declare the class in code module.  Exameple: Private Ogre As Monster
'5. Instantiate the object like so: Set Ogre = New Monster
'6. Use appropriate methods and the dot operator to assign values to the object.  Example:
'   Ogre.Life = LifePoints                  -> assigning a value
'   Ogre.Strength = lblStrength.Caption     -> interacting with a VB form object
'   Ogre.GoOnARampage()                     -> Invoking a member function

       'Class General Declarations
    Public MonsterLife As Integer
    Public MonsterStrength As Integer

    'Accesor methods
    Public Property Get Life()
           Life = MonsterLife
    End Property
    Public Property Let Life(Lif)
           MonsterLife = Lif
    End Property
    Public Property Get Strength()
           Strength = MonsterStrength
    End Property
    Public Property Let Strength(Str)
           MonsterStrength = Str
    End Property

  Public Function AttackPlayer() As String
         Dim SeriousPain
         Dim MonsterAttack As String
         If Functions.Life > 0 Then
         SeriousPain = RandomNumber(MonsterStrength, 1)
         Functions.Life = Functions.Life - SeriousPain
              Select Case (SeriousPain)
               Case 1
               MonsterAttack = " You loose 1 point - A mild skin abrasion. "
               Case 2
               MonsterAttack = " You loose 2 points - Merely a flesh wound. "
               Case 3
               MonsterAttack = " You loose 3 points - A moderate scrape. "
               Case 4
               MonsterAttack = " You loose 4 points - A nasty cut. "
               Case 5
               MonsterAttack = " You loose 5 points - A festering puss-filled gash. "
               Case Else
               MonsterAttack = " You loose 6 points - A heavy blow. "
              End Select
               MonsterAttack = " Oh . . . death, thy bitter sting awaits . . ."
         End If
        AttackPlayer = MonsterAttack
  End Function

Public Function AttackMonster() As String
         Dim SeriousPain
         Dim PlayerAttack As String
         If MonsterLife > 0 Then
         PutAHurtinOnIt = RandomNumber(6, 1)
         MonsterLife = MonsterLife - PutAHurtinOnIt
              Select Case (PutAHurtinOnIt)
               Case 1
               PlayerAttack = " It looses 1 point - you just made it angry! "
               Case 2
               PlayerAttack = " It looses 2 points - now it's really mad! "
               Case 3
               PlayerAttack = " It looses 3 points - it flies into a rage! "
               Case 4
               PlayerAttack = " It looses 4 points - yuk, green monster blood! "
               Case 5
               PlayerAttack = " It looses 5 points - it howls in pain. "
               Case Else
               PlayerAttack = " It looses 6 points - monster guts splatter against the wall. "
              End Select
                PlayerAttack = " You did it!  You killed the monster! "
            End If
        AttackMonster = PlayerAttack
  End Function

  Public Function Talk() As String
           Dim PlayerAttack As String
           Dim SayThis As Integer
           Dim WhatWasSaid As String   

           SayThis = RandomNumber(8, 1)
              Select Case (SayThis)
               Case 1
               WhatWasSaid = "I like flowers and butterflies."
               Case 2
               WhatWasSaid = "I love you man, I mean I really love you."
               Case 3
               WhatWasSaid = "Would you hold it against me if I said I'd like to eat" _
                         & " your brain?"
               Case 4
               WhatWasSaid = "#$%*(#$%!  (What a foul mouth! We'll have to upgrade" _
                         & " the game to PC-13!  Naughty monster.)"
               Case 5
               WhatWasSaid = "I hate people.  I mean I HATE them.  I want to destroy them all."
               Case 6
               WhatWasSaid = "Being the villian in your game is a demanding job - I'm beat!"
               Case 7
               WhatWasSaid = "O.k., let me get this straight.  You good guy, me bad guy." _
                       & " What's my inner motivation here?  I need some depth."
               Case Else
               WhatWasSaid = "Ever think that maybe I'm the poor, defenseless monster " _
                       & "and maybe YOU are the ruthless, invading barbarian?"
           End Select
           Talk = WhatWasSaid
  End Function


Dialog Boxes
The Common Dialog control provides a standard set of dialog boxes for operations such as opening, saving, and printing files, as well as selecting colors and fonts.   At design time, the control displays as an icon on the form.  Note that the icon is not resizable and its position does not matter, because it is not visible at run time.  Instead, at runtime, VB displays an appropriately sized dialog box in a default position in the interface.  You tell VB which type of dialog box to display, and when to display it, by including one of the Common Dialog control’s methods in an event procedure.  These methods include ShowOpen(), ShowSave(), ShowPrinter(), ShowColor(), and ShowFont(). 

The ShowOpen() method shows the name of the current folder and a list of filenames that depend on the entry in the “Files of type” list box.  The “filter” in the File of type list box refers to the extension on the file’s name.  The “*” is known as a wildcard; you can use it to represent any characters.  The standard description and filter for displaying all files in the current folder is “All Files (*.*)”.  The File name text box is empty when the Open dialog box appears.

The Filter property stores a string that represents both the description and the filter for the files displayed in the File name list box when either the Open or Save As dialog box appears.  The FileName property stores the name of the file that appears in the File name text box.  The Save As dialog box shows the name of the current folder and a list of filenames that depend on the entry in the Files of type list box.  The File name text box contains the name of the current file.  The file name selected by the user is stored in the FileName property.

The On Error statement - turns the error trapping process on.   Its syntax is:  On Error GoTo Line           Line:

"Line" is either a label or a line number that identifies the location of the error handler.  Labels can be any word in VB6 that ends with a colon (":").  Most programmers place this statement at the beginning of the procedure in which the errors they are attempting to trap may occur.  The specific coding depends on the kind of error that occurred and how you want to handle it.  Note that you should place an Exit Sub statement at the end of the procedure, but above the error handler code, so that the error handler code is not processed mistakenly (it should only be activated via the On error Go To line statement). 

The ADO Data Control

The ADO control establishes a link between the database and the other controls in the application’s interface.  Use the Project menu to add the ADO Data Control 6.0 (OLEDB) component to the toolbox, and then add an Adodc control to the interface.  An Adodc control has the prefix ado and is an instance of the Adodc control class.  An Adodc control has buttons including First Record, Last Record, Previous Record, and Next Record.  After adding the Adodc, you must set its ConnectionString property to establish a connection to the data source (e.g., the Cole database in the example covered in the Tutorial).  After setting the ConnectionString, set the Adodc RecordSource property, which tells the control which database records you want to access; the RecordSource property can be the name of a table or an SQL Select command.

After placing the Adodc on the form and setting its properties, you can connect the other controls in the form to it.  Connecting a control to an Adodc control on the form is called binding, and the connected controls are referred to as the data-aware controls or bound controls.  Note that any control that has a DataSource property can be bound to an Adodc control.

SQL stands for Structured Query Language and is a set of commands for accessing and manipulating data stored in a variety of database systems.  The most commonly used SQL command is Select, which allows you to select which fields and records you want to view, as well as the control order in which the fields and records appear when displayed.  Its syntax is

select fields from table [where condition] [order by field]


1)       fields is one or more field names, separated by commas

2)       table is the name of the table containing the fields

3)       where condition allows you to limit the records that are displayed according to some logical criteria

4)       order by field allows you to control the order in which the records appear.

SQL also has a Like operator that you can use in the where clause (along with the % wildcard character)
to match specific characters in a field.

Writing Code to Add, Delete, and Update Records

This lesson first explains the Recordset and Field objects.  The SQL Select command allows you to select one or more records from a database table.  VB treats the collection of selected records as an object, called a Recordset object.  For example, the command

                select * from tblPatron

creates a Recordset object that contains all the records stored in the tblpatron table.  Each field in a Recordset object is called a Field object.  The collection of fields in a Recordset is called the Fields collection.  Use the following syntax to refer to a specific field in the Field collection:


where field is the name of the field, enclosed in quotation marks.

A Recordset object has six predefined methods and an EOF property.  The methods include

1)       AddNew – adds a new, blank record to the end of the Recordset

2)       CancelUpdate – cancels the changes made to the current record

3)       Delete – deletes the current record from the recordset.

4)       MoveFirst – moves the record pointer to the first record in the recordset

5)       MoveNext - moves the record pointer to the next record in the recordset

6)       Update – saves the changes to the current record

7)       EOF property – true if the record pointer is after the last record in the recordset

Use the ADO Data control’s Refresh method to create a new Recordset object while an application is running.  Refresh reopens a database and recreates the Recordset object.  This is accomplished by coding adocontrol.Refresh.

The DataGrid Control

This lesson first covers the DataGrid control.  When bound to an ADO control, the DataGrid control displays the information from the recordset created by the ADO control’s RecordSource property.  The information displays in a row and column format, similar to a spreadsheet.  Each database filed appears in a column, and each record displays in a row.  The intersection of a row and column is called a cell. To include the DataGrid control use the Components option in the Project menu and add the Microsoft DataGrid Control 6.0 (OLEDB) tool to the toolbox, then place a DataGrid control on the form.  Use the prefix dgd for a DataGrid control.

You can bind the DataGrid control to the ADO data control by setting the DataGrid control’s DataSource property.  You can right-click the DataGrid control to view its popup menu.  The Retrieve option allows you to display the Recordset object’s field names.  The Edit control puts the DataGrid in Edit mode, which allows you to use a scroll bar.  The Properties option displays the Properties Pages dialog box, which allows you to control the appearance of the DataGrid’s control output as well as how the user can interact with the DataGrid control.

The Property Pages dialog box has many features.  You can use the Caption property to assign a title to the DataGrid control.  The General Tab contains five check boxes: AllowAddNew, AllowDelete, AllowUpdate, ColumnHearers, and Enabled.  The Columns tab allows you to change the column headings and their order of display.  The Format tab allows you to format numbers.  The Layout tab allows you to prevent the user from
making changes to one or more columns.  It also controls the alignment of text in the columns.

The five DataGrid events are summarized in Figure 10-42.  They include

1)       BeforeColUpdate – occurs after editing is completed, but before data is moved to the copy buffer.

2)       AfterColUpdate – occurs after data is moved to the copy buffer

3)       AfterColEdit – occurs after editing is completed, even if no changes were made

4)       BeforeUpdate – occurs after editing is completed but before the data is moved from the copy buffer to the ADO’s copy buffer.

5)       AfterUpdate – occurs after changed data has been written to the database.

Drag and Drop

Dragmode - a property of VB objects used to determine drag and drop behavior. 

Robin:  Jumpin' Jelly Beans, Batman!  Did you hear what he said?
Easy, Robin, old chum.  While I too find the idea of men wearing kilts to be patriotic and liberating, this is not what he was referring to.

When set to "1-Automatic", the user can drag the control across the form. 

DragIcon - property that determines icon to be displayed while dragging.  Example: imgPerson.DragIcon = imgPerson.Picture
DragDrop - event handler triggered by dragging and dropping an object or component.  Example Application - Tic Tac Toe:

Option Explicit
Private Sub cmdExit_Click()
    Unload TicTacToe
End Sub
Private Sub cmdNew_Click()

    'Clear the boxes on the screen
    Dim intX As Integer
    For intX = 0 To 8
        imgBox(intX).Picture = LoadPicture()
        imgBox(intX).Enabled = True
    Next intX

End Sub
Private Sub Form_Load()

    TicTacToe.Left = (Screen.Width - TicTacToe.Width) / 2
    TicTacToe.Top = (Screen.Height - TicTacToe.Height) / 2
    imgX.DragIcon = imgX.Picture
    imgO.DragIcon = imgO.Picture

End Sub
'Control array for images
Private Sub imgBoard_DragDrop(Index As Integer, _
Source As Control, X As Single, Y As Single)

    imgbox(Index).Picture = Source.Picture
    'Disable the box once an image is dropped into it
    imgBox(Index).Enabled = False

End Sub

Example of Drag and Drop Event Handling:

Download: quiz1.exe

Option Explicit
Private Sub cmdExit_Click()
    Unload Quiz1
End Sub
Private Sub cmdNew_Click()
  Dim intX As Integer
  For intX = 0 To 3
  If imgQuestion(intX).Picture = 0 Then
     imgQuestion(intX).Picture = imgAnswer(intX).Picture
     imgAnswer(intX).Picture = LoadPicture()
  End If
  Next intX
End Sub
Private Sub Form_Load()
  Dim intX As Integer
  Quiz1.Top = (Screen.Height - Quiz1.Height) / 2
  Quiz1.Left = (Screen.Width - Quiz1.Width) / 2
'Applicable if image objects were .ico files.
'For intX = 0 To 3
'imgQuestion(intX).DragIcon = imgQuestion(intX).Picture
'Next intX
End Sub
Private Sub imgAnswer_DragDrop(Index As Integer, _
Source As Control, X As Single, Y As Single)

    If Index = Source.Index Then
        imgAnswer(Index).Picture = Source.Picture
        Source.Picture = LoadPicture()
    End If
End Sub


The Clip Board

We are all familiar with the clipboard being used to transfer data from one application to another.   VB6 applications integrate with this Windows feature.

DDE - Dynamic Data Exchange.  A method of copying data from one windows application to another.  For DDE, both source and destination applications must be running.   You can also paste a link to data, using Paste Link, and if you should change data with the source application it will be reflected in the destination  application. 

OLE - Object Linking and Embedding.  the application that creates the data is called the source/server application and the application that receives the data is called the container/client application.  The difference between linking and embedding is where the object is stored.  When an object is embedded, a copy of it is stored with the receiving application.  When you link and object, it is shared among the applications (like passing by reference).  To embed objects in VB:

1. Open VB and create a form.  Select the form, then the "OLE tool" from the toolbox.
2. A box will appear listing the types of objects that can be linked or embedded.  Select "Create From File".
3. Select "Browse", then select a file.  Click "OK".   You can now edit what you embedded from within the Visual Basic form.

To save the data, you will need to open a binary access file.  The syntax is as follows:

Dim FileName As String
FileName = "spreadsheet.xls"
Open (App.Path & FileName) For Binary As #1

In OLE, we will use the OLE control's "SaveToFile" method to accomplish this.  To read from the binary file, we can use the OLE control's "ReadFromFile" method.  It is called by:  OLEObjectName.SaveToFile #1         or       OLEObjectName.ReadFromFile #1.      Example: 

Private Sub Form_Load()
    frmEmbed.Top = (Screen.Height - frmEmbed.Height) / 2
    frmEmbed.Left = (Screen.Width - frmEmbed.Width) / 2
    'open the binary access file that contains the saved object
    Open App.Path & "\ApCRegion.ole" For Binary As #1
    'read the binary access file
    oleSales.ReadFromFile 1
    'close the binary access file
    Close #1
End Sub
Private Sub mnuFileExit_Click()
    Unload frmEmbed
End Sub
Private Sub mnuFilePrint_Click()
End Sub
Private Sub mnuFileSave_Click()
    'open a binary access file
    Open "a:\appendc\ApCRegion.ole" For Binary As #1
    'save the contents of the OLE control
    oleSales.SaveToFile 1
    'close the binary access file
    Close #1
End Sub

update method - OLE control method to update data being displayed on a linked object.  Example:

Private Sub Form_Load()
    frmLink.Top = (Screen.Height - frmLink.Height) / 2
    frmLink.Left = (Screen.Width - frmLink.Width) / 2
End Sub

Active X Controls

Active X - allows creating cross-platform, language independent controls.  Example:

Creating a Custom Active X Control
1. Open VB, select "New Project", "Active X Control", then click "Open".
2. Set the custom control's "Name" property. 
3. Add a label, call it "Number".  Then add a horizontal scroll bar, call it "Scrollie", setting its Max property to 10.
4. Code the scroll bar control's "Change" event handler to the following:  Number.Caption = Scrollie.value
5. Add the same code to the scrollbar's "Scroll" event.
6. Save the Active X Control as "MyActiveXControl.ctl". 

Using a Custom Active X Control
1. Open VB, select "Add Project, "Standard EXE", the "Open".
2. Your custom  "MyActiveXControl.ctl" will be in the toolbox.  Add it to the form and run the program. 

Robin: Golly jeepers creepers Batman, Presto!  That sure was fast and easy!
Batman: Yes Robin, Visual Basic makes crime fighting a lot easier, even for my astoundingly deductive intellect!