Visual Basic 5-6 Course Part 4

19

Click here to load reader

Transcript of Visual Basic 5-6 Course Part 4

Page 1: Visual Basic 5-6 Course Part 4

Visual Basic 5 Programming - 4 A Specialised Training Course

Page 2: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 1

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

Page 3: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 2

Procedures; Subs & Functions As mentioned earlier in the course there are different types of procedures in Visual Basic.

• Event procedures

• User defined / General procedures

• External procedures (API, DLLs etc.)

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...

• Activated by user (clicking with mouse etc.)

• Triggered by system (timer event)

• Called by statements in other procedures

User defined / General procedures

If several event procedures perform the same actions you can duplicate the code in each. Then

it comes to changing that code you then need to edit it several times. Instead the code can be

extracted to a single general procedure and called from the event procedures. To create a new

general procedure open a code window for the form or module type a procedure heading in

the code window and press enter.

Visual Basic responds by creating a new template for the procedure that is now accessible in

the code window by selecting the [general] object and the relevant procedure. An alternative

way to access your procedures, especially when you have several forms/modules is to press

F2 when the code window is active to bring up a list of forms/modules and associated

procedures.

Comment [I1]:

Page 4: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 3

External procedures

Later in the course we shall explore the power available through external procedures. These

will allow us to...

• Utilise the Windows API functions and procedures.

• Create our own DLLs in other languages (C / C++) and utilise them in our Visual

Basic applications.

• Tap in to other applications DLLs (Excel ‘97etc.)

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

Page 5: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 4

Calling/Invoking Procedures

In book 3 we looked at how to access Sub procedures, we need to extend this to call

Function procedures.

To call a Sub procedure we could use the Call keyword or just place the name of the

procedure as a statement (considering the parentheses).

e.g.

Call procDoSomething(x , y) procDoSomething x,y

To invoke a Function procedure as you would any built in function, either as the right hand

side of an assignment, as part of a condition or even as an argument to something else. You

cannot use the Call statement with functions, but you must always use parentheses.

e.g.

ThirteenCubed& = Cubed(13)

If Cubed(x) > 100 Then... Call procDoSomething( Cubed(x), Cubed(y) )

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)...

Page 6: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 5

Passing by Reference

If an argument passed to a procedure is a variable it is actually passed by reference (i.e. the

address of the variable is passed). For numeric values this means that any change to the

variable within the procedure will effect the variable outside the procedure, even if you use a

different name. Strings are not affected in the same way due to the fact that they are

referenced differently.

e.g.

Sub Form_Load( ) A% = 10

print A% Call DoSomething( A% ) ‘ passing by reference print A%

End Sub

Sub DoSomething(X As Integer) ‘ receiving by reference

print X X = 20

print X

End Sub

This code would output 10, 10, 20, 20. A% equals 20 at the end although we changed it as X

within the DoSomething procedure.

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...

Page 7: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 6

Passing Arrays

If you want to pass an entire array as an argument you use the array name followed by a pair

of empty parentheses. The formal declared argument also uses a pair of empty parentheses.

e.g.

Dim MyArray%(4,5) Call ProcessArray( MyArray%() ) ...

Sub ProcessArray( ArgArray%() )

For FirstDim% = LBound(ArgArray%, 1) To UBound(ArgArray%,1) ...

Next FirstDim%

End Sub

The LBound and UBound functions are used to determine the array bounds within the

procedure.

If you want to pass a single array element you treat it as any other variable.

Passing Records / User defined Types

As long as you have defined your type correctly you can treat a record variable as any other

variable type. The passed variable and the formal declared argument must be of the same

type.

If you are passing a single record element, treat it as any simple variable.

Passing Control / Form properties

There may be occasions when you need to pass properties of controls and forms to

procedures. You may need to pass the Width and Height properties of a form to a procedure

that calculates the window size.

Passing Objects; Forms and Controls

There will even be occasions when you need to pass whole objects. This enables you to write

general procedures that perform similar actions on whatever object you pass (e.g. Set a

property such as width on a whole set of text boxes, specify a control to place a graphic into

etc.). We do not have time to discuss this in depth, but be aware that this is possible.

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.

Page 8: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 7

List and Combo Boxes Both the List and the Combo box controls can be used for selecting data from a list. The main

difference is that with List boxes you can only select items that already exist in the list; with

Combo boxes you can also type in your input similar to a text box. List boxes also allow

multiple selection modes and multi-column lists. In both controls scroll bars are

automatically added if the list is too large to display in the space provided.

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.

Adding and Removing Items

In order for our list to be of any use we need to be able to add and remove items from the list

property array. Both use similar Methods for adding and deleting list entries. These are...

• AddItem - for adding entries to a List / Combo Box

lstFlavour.AddItem “Vanilla”

• RemoveItem - for removing items from a List / Combo box

lstFlavour.RemoveItem 4

• Clear - Removes all items from a List / Combo box

lstFlavour.Clear

Page 9: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 8

A List Example Sub Form_Load()

lstDept.AddItem “Sales”

lstDept.AddItem “R&D” lstDept.AddItem “Accounts”

...

End Sub

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

Exclusive List Box Properties

So far we have seen single selection list boxes. List boxes have other possibilities.

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.

Page 10: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 9

Selected Property

The ListIndex property is of no use when we have multiple selection. To allow for any

combination we need to check all items to see if they are selected or not. This is indicated by

another property containing an array, the Selected Property. It is of the same size as the List

array, and each element contains a Boolean Integer to indicate whether...

• True - The corresponding list element is selected

• False - The corresponding list element is not selected

Exclusive Combo Box Properties

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.

SelLength, SelStart & SelText Properties

These properties determine where the cursors position from the beginning of the text and if

any of the text has been highlighted. Also these properties can be used to set the cursors

position anywhere along the text and to select a portion of the text as highlighted.

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.

Page 11: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 10

Grid Control

In essence a grid is effectively a two-dimensional table tool that holds data in rows and

columns, similar to a spreadsheet. The basic construct of a grid is a set of rows and columns,

the intersections of which create individual cells. Each cell can contain text, a number or even

a picture. There are two types of Grid Control available in Visual Basic 5. The first is the

Data Bound or DB Grid . This is used primarily for linking to a data source such as a

database. It is better to think of the DBGrid as a combination of a RecordSet object and a

Collection of Column objects. The other is the Flex Grid. The main use for the FlexGrid is

representing data in tabular form. Pictures can also be displayed in the cells of the FlexGrid.

To enable column and row headings it is possible to fix a number of rows and columns

(usually one of each). Fixed rows and columns appear shaded and their contents can not be

changed. At any given time there will be at least one single selected / highlighted cell. It is

also possible to select a rectangle of cells by clicking and dragging.

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:

Design Time Properties

The subset of properties described here may also be set at runtime. Whilst DBGrids have

design-time properties, they are the more esoteric ones and as such are left to the reader to

look up. We shall only deal with the design time properties of FlexGrids for now.

Rows, Cols, FixedRows, FixedCols Properties

Using Rows and Cols, one can set the initial size and appearance of the FlexGrid within the

control frame drawn on the form. It is possible for the space on the form (the frame) to be

larger or smaller than the actual contained grid. If the grid is too large for the frame then

scroll bars automatically appear (unless disabled by ScrollBars property) to navigate around

the grid.

Fixed Rows begin at the top and fixed columns from the left. If scroll bars are required then

the fixed rows and columns remain visible, but correspond to the normal cells on display and

the columns and rows are scrolled across or up/down the screen.

Fixed Column

Fixed Row

Unfixed Cell

Highlighted

Cell

Page 12: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 11

At runtime these values can be changed to alter the size of grid. They can also be referenced

for the current values.

HighLight Property

Contains True or False; False turns off the highlighting of cells.

GridLines, GridLineWidth Properties

GridLines also contains True or False; False turns off the display of gridlines around each

cell. If True then the width of the gridlines is determined by GridLineWidth.

Run-Time Properties

Row, Col Properties ( FlexGrid, DBGrid )

Not to be confused with the Plural versions described above, these two properties indicate the

row and column of the highlighted cell. If a rectangular range of cells is selected, then they

indicate the current top-left cell in the range.

Text Property( FlexGrid, DBGrid )

To add or reference the contents of a cell, the simplest property is the Text property. It applies

to the cell defined by Row and Col.

SelStartRow, SelEndRow, SelStartCol, SelEndCol Properties ( DBGrid)

These properties are more informative than Row and Col. They indicate the start and ending

row and column values for the selected range.

ColSel, Rowsel (FlexGrid)

These are the FlexGrid versions of the previous DBGrid properties. The contents of the

selected range are stored as a single string in the Clip property.

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.

ColAlignment, FixedAlignment Properties(FlexGrid)

These determine the text alignment within specific columns. ColAlignment is used for

normal Columns and FixedAlignment for fixed columns. The possible values are...

Value Alignment

0 Left (default)

1 Right

2 Centre

To change the property you must specify which column to change...

Page 13: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 12

gridname.ColAlignment(ColumnNumber) = value

In order to change a range of cells you should use a For...Next loop.

Width,Height(DBGrid) & ColWidth, RowHeight Properties(FlexGrid)

Each column can be given an individual width, referenced with the Width or ColWidth

property. As well as setting this explicitly within code the user can change the column width

by clicking and dragging the gridline between fixed row cells.

Similarly, each row can have an individual height, referenced with the Height or RowHeight

property. It can also be changed by dragging the gridlines between fixed row cells.

If you insert text that is too large to be displayed in a cell you will need to change the size of

the cell one way or other. The text automatically wraps around to multiple lines if the column

is not wide enough ( and if the Wordwrap property is set to true ), but if the height is not

enough it will not be displayed fully.

Page 14: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 13

Grid Control Methods

The Grid controls have several methods that allow you to add and remove rows and columns.

The way in which you do so depends on which type of grid you are using. For DBGrids the

number of rows is determined by the RecordSet object and to add/remove columns the

methods of the Columns Collection has to be used.

AddItem Method (FlexGrid)

A familiar method name, but a different context. The syntax is as follows...

gridName.AddItem string[,index]

The string is Tab delimited, and can be more than a single row (using Carriage Return). If

specified, the Index indicates the position to insert the row, otherwise it is added to the end.

RemoveItem Method (FlexGrid)

Syntax...

gridName.RemoveItem index

The index must be included to indicate the row number to delete. To remove the last row you

can use (gridName.Rows-1) as the index.

Add (Columns)

Syntax…

object.Add colindex

Adds a new column to the Columns collection. The settings for colindex are:

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.

Page 15: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 14

Using Grids

As very little can be set at design-time, a lot of initialisation must be done at Run-Time.

One of the problems is how to set-up the fixed columns and rows. You cannot set their

contents at design-time, neither can you alter their contents once fixed at RunTime. Your

Form_Load or alternative initialisation procedure should do the following...

• Set the FixedCols and FixedRows to 0 (zero)

• Use gridname.AddItem heading_string, 0 to insert the row(s) containing

the column headings.

• Introduce a loop to add Row headings down the left hand column(s).

• Set the FixedCols and FixedRows properties to the relevant values.

Page 16: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 15

Exercises

Preparation:

Create sub-directories for the following projects...

• ARGS

• MYGRID

Exercise 1

This exercise illustrates passing arguments by reference and by value. As the purpose

is purely academic we won’t bother making it look pretty.

1. On your blank Form1 place 8 single line Label controls in two groups of four, one

under the other. Leave the names and captions as they are.

2. Create a general procedure called Change_String containing the following code...

Sub Change_String (argText As String) Label2.Caption = "Sub in: " + argText

argText = "I'm argText in a procedure"

Label3.Caption = "Sub out: " + argText

End Sub

3. Create another general procedure, this time called Change_Numbers...

Sub Change_Numbers (X%, y!)

Label6.Caption = "Sub in: X = " + Str$(X) + "; Y = " + Str$(y) X = 50

y = 12.345

Label7.Caption = "Sub out: X = " + Str$(X) + "; Y = " + Str$(y)

End Sub

4. Add the following code to the Form_Load procedure...

Sub Form_Load ()

'how do strings behave?

MyText$ = "This is me as defined by Form_Load"

Label1.Caption = "pre-Sub: " + MyText$ Change_String MyText$

Label4.Caption = "post-Sub: " + MyText$

'how do numbers behave?

A% = 100

B! = 123.45

Label5.Caption = "pre-Sub: A = " + Str$(A%) + " ; B = " + Str$(B!)

Call Change_Numbers(A%, B!)

Label8.Caption = "post-Sub: A = " + Str$(A%) + " ; B = " + Str$(B!)

End Sub

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)

Page 17: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 16

Exercise 2

In this exercise we shall investigate the properties and functionality of a grid.

If you haven’t already done so start a new project.

1. Place the following controls on the form as shown in the diagram and giving your

objects the property values shown in the table overleaf...

Type Name Caption / Text Other...

Form frmMygrid My Grid

FlexGrid grdMyGrid n/a remove all columns

Label Label1 none

Label2 none

Label3 none

Label4 none

Text Box txtEdit none

Command Button cmdEdit(0) &Cut

cmdEdit(1) C&opy

cmdEdit(2) &Paste

Page 18: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 17

2. First we need to set up the Grid with some row and column headings. Place the

following code in the Form_Load procedure.

'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$

Page 19: Visual Basic 5-6 Course Part 4

Visual Basic Book 4 © Mark Collins 1999 Page 18

Label2.Caption = "Col:" & Chr$(grdMyGrid.Col + 64) & " to " & Chr$(Val(ColText$) + 64)

7. Save and test your project.

8. Add to the shared cmdEdit_Click procedure as follows...

Static MyClip As String Select Case Index

Case 0 ' Cut MyClip = grdMyGrid.Clip

grdMyGrid.Clip = "" Case 1 ' Copy

MyClip = grdMyGrid.Clip Case 2 ' Paste grdMyGrid.Clip = MyClip

End Select

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?