Professional Documents
Culture Documents
Programming - 4
A Specialised Training Course
Contents
PROCEDURES; SUBS & FUNCTIONS ............................................................................................................ 2
EVENT PROCEDURES ........................................................................................................................................ 2
USER DEFINED / GENERAL PROCEDURES .......................................................................................................... 2
EXTERNAL PROCEDURES .................................................................................................................................. 3
SUB VS FUNCTION ............................................................................................................................................ 3
Sub Procedure .......................................................................................................................................... 3
Function Procedure.................................................................................................................................. 3
CALLING/INVOKING PROCEDURES .................................................................................................................... 4
PASSING ARGUMENTS ...................................................................................................................................... 4
Passing by Reference ............................................................................................................................... 5
Passing by Value ...................................................................................................................................... 5
Passing Arrays ......................................................................................................................................... 6
Passing Records / User defined Types ..................................................................................................... 6
Passing Control / Form properties........................................................................................................... 6
Passing Objects; Forms and Controls ..................................................................................................... 6
STATIC KEYWORD ............................................................................................................................................ 6
PRIVATE KEYWORD.......................................................................................................................................... 6
LIST AND COMBO BOXES .............................................................................................................................. 7
SHARED PROPERTIES ........................................................................................................................................ 7
List Property............................................................................................................................................. 7
ListIndex Property.................................................................................................................................... 7
ListCount Property ................................................................................................................................... 7
ItemData Property.................................................................................................................................... 7
Adding and Removing Items..................................................................................................................... 7
A List Example ......................................................................................................................................... 8
EXCLUSIVE LIST BOX PROPERTIES ................................................................................................................... 8
Columns Property .................................................................................................................................... 8
MultiSelect Property................................................................................................................................. 8
Selected Property ..................................................................................................................................... 9
EXCLUSIVE COMBO BOX PROPERTIES .............................................................................................................. 9
Style Property........................................................................................................................................... 9
SELLENGTH, SELSTART & SELTEXT PROPERTIES ............................................................................................ 9
SelStart ..................................................................................................................................................... 9
SelLength.................................................................................................................................................. 9
SelText ...................................................................................................................................................... 9
DESIGN TIME PROPERTIES .............................................................................................................................. 10
Rows, Cols, FixedRows, FixedCols Properties ...................................................................................... 10
HighLight Property ................................................................................................................................ 11
GridLines, GridLineWidth Properties.................................................................................................... 11
RUN-TIME PROPERTIES .................................................................................................................................. 11
Row, Col Properties ( FlexGrid, DBGrid ) ............................................................................................ 11
Text Property( FlexGrid, DBGrid )........................................................................................................ 11
SelStartRow, SelEndRow, SelStartCol, SelEndCol Properties ( DBGrid) ............................................. 11
ColSel, Rowsel (FlexGrid)...................................................................................................................... 11
Clip Property(FlexGrid)......................................................................................................................... 11
ColAlignment, FixedAlignment Properties(FlexGrid) ........................................................................... 11
Width,Height(DBGrid) & ColWidth, RowHeight Properties(FlexGrid) ................................................ 12
GRID CONTROL METHODS.............................................................................................................................. 13
AddItem Method (FlexGrid)................................................................................................................... 13
RemoveItem Method (FlexGrid)............................................................................................................. 13
USING GRIDS .................................................................................................................................................. 14
EXERCISES........................................................................................................................................................ 15
Event procedures
As each object instance is created (creation of a control or form) the object type automatically
creates a set of event procedures that you may wish to use. Initially they are all empty (i.e.
consist of Sub Control_Event( ) and End Sub lines). It is left to you the developer
to add the relevant code to the events you want to react to. Generally one or two of the
possible events for each object instance are developed, but most remain unused.
As we saw in book 3 it is possible to create Control Arrays which share event procedures. In
this situation, an argument / parameter identifying the specific element is passed to the
procedure by the system.
Event procedures can be activated by several methods...
Comment [I1]:
• Activated by user (clicking with mouse etc.)
• Triggered by system (timer event)
• Called by statements in other procedures
Sub vs Function
There are two types of procedure Sub or Function. Event procedures are always Sub
procedures, it is only general and external procedures that can be Function procedures.
Sub Procedure
Sub procedures do not return a value. A sub procedure can however be passed arguments (aka
parameters, but see below) as to allow specification and sharing of data.
The syntax of a Sub procedure is as follows...
Sub procedurename(ArgList)
statement block
End Sub
The Sub procedure name must be unique and can not be shared with any variable or other
procedure within the same scope. The naming rules are the same as variables (40 characters
max, only underline punctuation).
Function Procedure
Function procedures do return a value as well as allowing arguments to be passed to them.
The syntax of a Function procedure is...
Function procedurename(ArgList)
statement block
procedurename = return value
End Function
For example, a function called Cubed that returns the cube of an integer passed to it might be
defined as follows...
Function Cubed(A as Integer)
Dim Cube as Long
Cube = A * A * A
Cubed = Cube
End Function
Passing Arguments
First let us get our terminology straight. I have always believed that you pass values /
switches as arguments to a function/program/procedure entity (the external view). From the
entity’s perspective it receives parameters (the internal view).
Microsoft’s terminology is different. It calls them arguments from both internal and external
views. The only use they make of the term parameter in Visual Basic is in relation to SQL
queries. As it’s their ball we’d better do things their way , just as we use dialog.
The argument list (ArgList in the syntax above) can be empty, a single argument or a
comma delimited list of arguments. The number of arguments in the procedure definition and
the number of arguments in a call must be identical, as must the type of each. Each argument
must have a data type assigned to it in one of the following ways...
• an As clause in the procedure definition
• A type-declaration character in definition
e.g.
Sub procDoSomething( x%, y%) ... or
Sub procDoSomething( x As Integer, y As Integer)...
Passing by Value
To prevent the problems of passing by reference you can specify to pass the value of the
variable rather than the address, as if we passed a literal, constant or expression. There are
two ways of doing this...
• place the argument within parentheses making it an expression, allows for a choice
each time you call the procedure
• Declare the argument with the ByVal keyword in the procedure declaration. All
calls pass that parameter by value.
In the above example one of the two commented lines would need to change...
Call DoSomething( (A%) ) ‘ passing by value
Sub DoSomething(ByVal X As Integer) ‘ receiving by value
Comparison
This situation is markedly different from other languages such as C.
In C the ‘default’ is to pass variables by value and variable pointers are required to pass
variables by reference.
You have been warned...
Static Keyword
If a procedure is defined with the Static keyword all variables local to the procedure are static
rather than being initialised each time the procedure is called. Can be used with Subs and
Functions.
Private Keyword
By default a procedure defined at form level is available throughout the form. General
procedures defined at Module level however are available globally to all forms and modules.
To prevent this we can add the Private keyword before Sub or Function to limit its
availability to the Module alone.
Shared Properties
List Property
In order to store the list data in the control there is a List Property. This property actually
contains an array in which each item in the list is an element of the array. This allows us to
access the individual elements as any other array using a subscript, the syntax for such a
reference is as follows...
control.List(Index)
ListIndex Property
This raises the question of which element to access. In a single selection mode the currently
selected item is contained in the ListIndex property which can only be manipulated at
runtime. If no item is selected it contains the value -1. If an item is selected we can use this
value as a subscript to access the relevant element. A trick you can use is to set this property
in code that also generates a click event for the control.
ListCount Property
This property contains an integer representing the number of entries in the list.
Be aware that the subscript range starts from 0 whereas the Listcount is a cardinal value, so
the final element’s subscript is equivalent to... ListCount-1
ItemData Property
This property also contains an array of long integer values. The array is of the same size as the
List property array and is used for associating a number with a list entry.
Sub cmdOK_Click()
If lstDept.ListIndex = -1 Then
MsgBox (“You must select a department”)
Else
MsgBox(“You chose ” & lstDept.Text)
‘MsgBox(“You chose ” & lstDept.List(ListIndex)) does same
End If
End Sub
Columns Property
The value determines the number of columns and the direction of scrolling for the list.
Value Effect
0 (Default) Items are arranged in a single column and the list box scrolls vertically.
1 to n Items are arranged in snaking columns, filling the first column, then the second
column, and so on. The list box scrolls horizontally and displays the specified
number of columns.
MultiSelect Property
This property determines whether multiple selection is allowed, and what method of selection
applies if so.
Value Effect
0 (Default) Multiple selection is not allowed.
1 Simple multiple selection. A click or the Spacebar selects or deselects an item in
the list. (Arrow keys move the pre-select focus.)
2 Extended multiple selection. Shift+click or Shift+arrow key extends the selection
from the previously selected item to the current item. Ctrl+click selects or
deselects an item in the list.
Style Property
This property determines the style of the combo box as follows...
Value Style
0 (Default) Dropdown Combo. Includes a drop-down list and an edit area. The user
can select from the list or type in the edit area.
1 Simple Combo. Includes an edit area and a list that is always displayed. The user
can select from the list or type in the edit area. The size of a Simple Combo box
includes both the edit and list portions. By default, a Simple Combo box is sized so
that none of the list shows. Increase the Height property to show more of the list.
2 Dropdown List. This style only allows selection from the drop-down list.
SelStart
This property sets or determines the position of the cursor along the text, starting from the left
hand side with a value of zero up to the length of the text to the right hand side of the text.
SelLength
This property sets or determines the length of the selected (highlighted) text, starting from
zero as no text highlighted up to the length of the whole text. Setting the SelLength greater
than the text length will set the whole text as selected and set SelStart to zero.
SelText
This property returns the text that is selected or replaces the highlighted text with some other
text; in the latter case, acts as equivalent to a paste function to replace the selected text.
Unfixed Cell
Fixed Column
One aspect of Grid controls are the numerous Runtime-only controls. Most other controls let
you set up default values for most properties at design-time, but not with Grids. Therefore
most of the setting up of a grid occurs at runtime, usually within a Form_Load event
procedure. Grid controls require a bit more setting up than other controls such as say, Text
Boxes, particularly DBGrids, which requires using the properties and methods of the column
objects as well as those of the Grid. Due to the nature of this course we haven’t time to cover
them in great detail. However, the salient features of both kinds of Grid are covered:
HighLight Property
Contains True or False; False turns off the highlighting of cells.
Run-Time Properties
Clip Property(FlexGrid)
The Text property is limited to a single cell, but the Clip property can contain the contents of
a whole range of selected cells. As with the whole grid, the values are stored in a single string
delimited with Tabs and Carriage Returns.
Setting Description
0 Inserts new column as leftmost column.
Count If the colindex argument is the same as the Count property setting, the new
column is inserted as the rightmost column.
n Inserts the new column to the left of the nth column in the Columns
collection. The nth column and all subsequent columns are incremented
accordingly.
Remove (Columns)
Syntax…
object.Remove index
Removes the specified Column object from the Columns collection of a DBGrid control.
5. Before you run the application try to predict what the results will be.
6. Save the Form and Project as ARGS.FRM and ARGS.VBP in the relevant project
directory and then run the application. Are your predictions correct?
7. Firstly amend only the Form_Load procedure to pass the values of A% and B! to
Change_Numbers by value by placing them in expressions.
8. Reverse your amendment of part 7 and now alter the Change_Numbers procedure to
achieve the same result. (hint ... ByVal)
'set-up headings
grdMyGrid.Cols = 6
grdMyGrid.Rows = 6
For m = 1 To 6
grdMyGrid.ColWidth(m - 1) = 575
grdMyGrid.ColAlignment(m - 1) = 2
Next m
For n = 2 To 6
grdMyGrid.Col = n - 1
grdMyGrid.Row = 0
grdMyGrid.Text = Chr$(n + 63)
grdMyGrid.Row = n - 1
grdMyGrid.Col = 0
grdMyGrid.Text = n - 1
Next n
How does this compare with the routine described on page 14?
3. Let us next get the text box linked to the grid. To automatically copy the contents of a
the active cell to the text box and make the text box the focus we need to develop the
grdMyGrid_Click procedure by adding the following lines...
txtEdit.Text = grdMyGrid.Text
txtEdit.SetFocus
4. Now to reflect any editing made to the text box in the selected cell we need to develop
the txtEdit_Change procedure.
grdMyGrid.Text = txtEdit.Text
5. Save your form and project as MYGRID.FRM and MYGRID.VBP in the relevant
project directory. Run the application as it stands. See how we have linked the text
box and grid in a seamless manner.
6. Now to display some useful information about the grid in the labels.
Label1 and Label2 will show some fancy range information based upon the ***Sel
properties. Place the following code before the existing contents of grdMyGrid_Click.
RowText$ = grdMyGrid.RowSel
ColText$ = grdMyGrid.ColSel
Label1.Caption = "Row:" & Str$(grdMyGrid.Row) & " to "
& RowText$
You may notice that our cut and paste does not work as efficiently as it would in say
Excel, especially when we have different shaped selections. See if you can resolve
any of these.
Some of the parameters used to set up the Grid can be set from the properties box at
design time. Do you think it is better to set them like this or using code to set it at run
time?