Classes/Collections Tutorial by Kevin Wiegand. Please download the Zip file that contains the source code if this tutorial is hard to read due to formatting problems.
Definitions:
Module
A term
used to describe where code is stored within Visual Basic. The three type of modules are (1) Form
Modules, (2) Standard Modules, and (3) Class Modules.
Standard Module
A type of
Module that contains (or should contain) publically accessible code, in other
words, code that is available to any module.
Class (Module)
A type of
module that allows you to create objects that contain your customized
properties and methods. (The Standard
Form (Default:Form1) is actually a Class Module!)
Object
An Object
is a Control (TextBox, Label), or it can be a Variable that defines an instance
of a Class.
Object Oriented
Programming (OOP)
Simply
put, OOP is programming with objects.
Collection
A
Collection is simply a group of related Objects.
Why use Class Modules?
Class modules, as said
before, offer a very useful tool - objects.
Classes can has multiple instances of its code, and each instances
properties/methods belong to that instance only. Standard Module code can only exist once.
Lets see an example!
All these definitions,
and a short explanation of Class Modules vs Standard Modules - you need to see
code, right? OK, start Visual Basic,
and start a new Standard Exe Project.
Add a Class Module. Rename
Project1 to ClassTest; Form1 to frmMain; Class1 to clsClassTest. Paste the following code into each respective
module, and then save the project:
frmMain:
***Start Copy***
'Require Variable Declaration (I believe that VB.Net already requires
that you
'declare all your variables before use - not only does this save
memory, but
'it also saves you the hassle of keeping track of things!)
Option Explicit
'This defines a Collection, it is empty right now, but we will fill it later
:)
Private fClassCollection As New Collection
'We'll use Form_Keypress instead of using a bunch of CommandButtons -
this is easier
'to do for this example
Private Sub Form_KeyPress(KeyAscii As Integer)
Select Case Chr(KeyAscii)
Case "a"
AddItemToCollection
Case "f"
ReturnNamesByFunction
Case "o"
PrintNames
Case "p"
ReturnNamesByProperty
Case "s"
ReturnNamesBySub
Case " "
ClearCollection
End Select
End Sub
Private Sub Form_Load()
'Set initial Form
properties, if you want, just set the properties in the Properties
'Pane, and remove this code
Me.ScaleMode = vbPixels
Me.Width = Screen.Width
Me.Height = Screen.Height
Me.Move 0, 0
'Lets us know how many
Objects in our Collection (should be zero right now)
Me.Caption = "Total
Names in Collection is " & fClassCollection.Count
End Sub
Private Sub AddItemToCollection()
'This is what creates a new
instance of the Object 'ClassTest'
Dim clsNewClass As New
clsClassTest
Dim strName As String
'This sets the Property
'Name' for the ClassTest Object
clsNewClass.Name =
InputBox("Enter a name:")
'This adds the newly created
Object to the Collection
fClassCollection.Add
clsNewClass
'You need to 'close' the new
Collection Object in order to add another one.
Set clsNewClass = Nothing
'Lets us know how many
Objects in our Collection
Me.Caption = "Total
Names in Collection is " & fClassCollection.Count
End Sub
Private Sub ClearCollection()
'This creates an Object
Variable that will hold references to the Objects in
'the Collection
Dim Obj As Object
For Each Obj In fClassCollection
'This uses the LIFO
(Last In First Out) method to remove each Object in the
'Collection, putting in
'1' in place of fClassCollection.Count will use the
'LILO (Last In Last Out)
method to remove each Object in the Collection.
fClassCollection.Remove
fClassCollection.Count
Next Obj
'Lets us know how many
Objects in our Collection (should be zero right now)
Me.Caption = "Total
Names in Collection is " & fClassCollection.Count
End Sub
Private Sub PrintNames()
'This creates an Object
Variable that will hold references to the Objects in
'the Collection
Dim Obj As Object
'Clear the form first
Me.Cls
'Print out a litle message
Me.Print "The following
" & fClassCollection.Count & " names are in the
Collection:" & vbCrLf
For Each Obj In
fClassCollection
'This calls the Method
to Print the Names currently in the Collection
Obj.PrintName Me
Next Obj
End Sub
Private Sub ReturnNamesByFunction()
'This creates an Object
Variable that will hold references to the Objects in
'the Collection
Dim Obj As Object
For Each Obj In
fClassCollection
'This calls the Method
to Return the Names currently in the Collection, and then
'MessageBox it to you,
note that this is actually a function instead of a sub as
'from the MsgBoxNames
procedure
MsgBox Obj.ReturnName,
vbOKOnly + vbInformation
Next Obj
End Sub
Private Sub ReturnNamesByProperty()
'This creates an Object
Variable that will hold references to the Objects in
'the Collection
Dim Obj As Object
For Each Obj In
fClassCollection
'This calls the Method
to Return the Names currently in the Collection, and then
'MessageBox it to you,
note that this is actually a function instead of a sub as
'from the MsgBoxNames
procedure
MsgBox Obj.Name,
vbOKOnly + vbInformation
Next Obj
End Sub
Private Sub ReturnNamesBySub()
'This creates an Object
Variable that will hold references to the Objects in
'the Collection
Dim Obj As Object
For Each Obj In
fClassCollection
'This calls the Method
to MessageBox out the Names currently in the Collection
Obj.MsgBoxName
Next Obj
End Sub
***End Copy***
clsClassTest:
***Start Copy***
Option Explicit
'These are internal variables that any one particular instance of this
Class can see
'This holds the Name Property
Private fstrName As String
'These hold the Max and Min sizes for the GenerateRandomText Function
Private Const fcMin = 5
Private Const fcMax = 10
'This sets the Name Property, it is based off of the Private 'fstrName'
Variable
Property Let Name(ByVal strName As String)
If strName = ""
Then
'This will call the
Private Sub to create a random jumbled string for the
''Name' property if the
user add a name that is empty
Randomize Timer
GenerateRandomText (Rnd
* (fcMax - fcMin)) + fcMin
Else
fstrName = strName
End If
End Property
'This returns the Name Property, it also must be based on the Private
'fstrName' Variable
Property Get Name() As String
Name = fstrName
End Property
'This is a simple Private Procedure contained in this Class. Any new instance of this class
'cannot specifically call this Procedure, it can only be called by
itself
Private Sub GenerateRandomText(ByVal intSize As Integer)
Dim lngCounter As Long
Dim strTemp As String
Dim bytRnd As Byte
Randomize Timer
For lngCounter = 1 To
intSize
bytRnd = CByte((Rnd *
(Asc("z") - Asc("a"))) + Asc("a"))
strTemp = strTemp &
Chr(bytRnd)
Next lngCounter
Name = strTemp
End Sub
'This is a simple Public Procedure contained in this Class. Any new instance of this class
'can specifically call this Procedure
Public Sub MsgBoxName()
MsgBox fstrName, vbOKOnly +
vbInformation
End Sub
'This is a simple Public Procedure contained in this Class. Any new instance of this class
'can specifically call this Procedure
Public Sub PrintName(ByVal destObj As Object)
'Notice how I called the
Property 'Name' instead of referencing the 'fstrName' Variable
destObj.Print Name
End Sub
'This is a simple Public Function contained in this Class. Any new instance of this class
'can specifically call this Function
Public Function ReturnName() As String
ReturnName = fstrName
End Function
***End Copy***
To use this example you can:
type 'a' to add a name
to the collection, leave the input box empty to create a random string
type 'f' to MessageBox
the names in the Collection, called using a Function in the Class
type 'o' to print the
name in the Collection, called using a Procedure in the Class that contains a
Private Procedure within the Class.
type 'p' to MessageBox
the names in the Collection, called using the Name Property in the Class
type 's' to MessageBox
the names in the Collection, called using a Procedure in the Class
type ' ' (spacebar) to
clear the Collection
Final Notes:
In this tutorial, you
should have learned how to create and use Class Modules. You have learned how to create and use Class
Properties, and you have learned how to create and use Class Methods (Methods
as Public Procedures, Methods as Public Functions, and Methods as Private
Procedures). You have also learned how
to use Collections. You have learned
how to Add Objects to a Collection, and Remove Objects from a Collection, as
well as loop through each Object in a Collection.
If you find any bugs
or problems with this tutorial, please let me know! If you have anything to add or comment on, please let me
know! If you have found this tutorial
helpful, please vote! I can be reached
at [email protected], or visit my WebSite at
http://www.geocities.com/wieganka, or my mirror site at http://4.41.60.122