You are on page 1of 71

Programming in visual basic

It is a window based programming language that evolved from DOS based BASIC programming language. Visual refers to the method used to create the graphical user interface (GUI). BASIC is the abbreviation for Beginners All purpose Symbolic Instruction Code. Visual basic has evolved from the original and other tasks. In most case, the user has no need to worry about API functions. You just have BASIC language and now contains several hundreds statements, functions and keywords many of which relate directly to the windows (GUI). VB provides an integrated development environment (IDE) in which you can develop, run, test and debug your applications. It also integrates many different functions such as design, editing, compiling and debugging within a common environment. Visual basic is also an object oriented programming language i.e. it revolves around ready made objects and its also an event driven i.e. all the activities in a program are triggered by one event or another. Each object has its own properties determining its position, size, color, appearance and nature of its text and much more. Each object has also its own event handling procedures. The programmers job is to determine where, how and when an object appears in the screen, what its caption reads and what happens when an event occurs. Visual basic supports application programming interface (API). API is the library of shared code that all windows application use for tasks like creating and displaying, windows, drawing text and graphics on the screen, tracking mouse clicks to click and drag controls and write basic codes. Visual basic does the work of translating these elements into API functions behind the scenes.

VISUAL BASIC DEVELOPMENT ENVIRONMENT


Using VB one can easily design the visual elements of a new programming project. The following types of applications can be created using visual basic: I. Standard exe Standard exe project I a typical application which contains a form by default. Use this project template to develop a stand-alone application. II. Data project This project contains a data environment and a data by default use this project template to develop an application that reads or manipulates data from a data source. III. Active X EXE /Active X DLL These projects are available with the professional edition of vb. These project templates are used to develop components that expose functionality to other applications .use an active x exe projects if your components will both explore functionality programmatically and run as stand alone application and use an an active x DLL project templates if your component will only be used programmatically by another application IV. ACTIVE X CONTROL This project type is also packaged with the professional edition of vb.this template is used to create active x controls use this project template to create a component design to use interface element in a form or dialogue box V. ACTIVE X DOCUMENT EXE /ACTIVE X DOCUMENT DLL Active X documents are visual basic applications that can run in the environment of a container that support hyper linking. Use these project templates to create components designer for use in a document object container such a internet explorer. VI. DHTML APPLICATION These applications are a combination of compiled visual basic and dynamic Html. Use this project template to create a component that can be used on the client side of a web application. VII. IIS APPLICATION Prepared By Fred Lisalitsa @computer Studies Department 1

This is a server based project that derives html and other internet contents to client browsers. use this project template to create a component that can be used on a server side of a web application

VISUAL BASIC IDE ELEMENTS


1. The menu bar It presents visual basic menu which contains commands which you use to work with. These include: a) File file handling and printing also used to make EXE files b) Edit standard editing functions c) View displays or hides windows and toolbars d) Project sets projects properties, adds or removes forms and modules and adds or removes reference and components e) Format aligns or sizes controls f) Debug- starts or stop debugging and stepping through programs g) Run- starts a program or compiles and starts it h) Tools- adds procedures, starts the menu editor and sets IDE options i) Add-ins adds in manager, lists, add-ins like application wizards and API viewer window j) Window arranges or select open windows k) Help it handles help and the about box 2. Tool bar It contains buttons matching popular menu items. it provides quick access to commonly used commands in the programming environment. 3. The project explorer Its the window that allows you to co-ordinate the parts of your program into folders for easy manipulation. It lists the forms and modules in your current project. A project is a collection of files you are to build an application. To pick out the part of the project you want to work on you only have to find it in the project explorer and double click it. You can also add or remove items by right clicking them with the mouse in the project explorer. The buttons at the top of the project explorer allows you to switch between views. 4. The properties window. Its a window used to set properties of various objects. When you select an object like a control in the VB using the mouse, that object properties appear in the properties window. To change or examine a property setting in the properties window you just find that propertys item in the window. 5. Object browser It provides you with an overview of all the objects in a project, including their properties and methods and what parameters to pass. You can see the object browser to explore objects in VB and other applications 6. The tool bar It provides asset of tools that you can use at design time to place controls on a form. You do this by just clicking a tool and draw the new button in a form 7. The form layout window Its used to position forms as you want them to appear in the screen when they are first displayed. This is done by dragging that form in the form layout window to that new location. 8. Form designers windows. The form designer displays the current form under design. It serves as a window that you customize. To design the interface of your application, you add controls, graphics and pictures to a form to create the look you want. Prepared By Fred Lisalitsa @computer Studies Department 2

9. Code editor window It serves as an editor for entering application code. A separate code editor window is created for each module in your application. To open an objects code in the code window, just double click that object or right click then close code editor. There are two drop-down list boxes at the top of the code window ;the left lists lets you select the object to add code to, and the right lists lets you select the p[procedure to add{all the methods the object supports appear in this list} 10. Context menus It contains short cuts to frequently performed actions. To open a context menu, click the right mouse button on the object you are using. STAGES IN APPLICATION DEVELOPMENT Program statements in an event driven application execute only when a specific event calls a section of a code assigned to that event. Creating event driven programs in VB requires an approach different from that used in procedural languages. Creating an application involves each of the following steps i. Create a design plan The design plan should be the road map you use when creating an application. This planning will help you to understand users needs and be more efficient in your development efforts. ii. Create the user interface To create the interface for your application, first place controls and objects on a form by drawing or painting in the form designer then position the controls and objects according to your need iii. Set the properties of the interface Once you have added objects to a form, you can set their properties at design time or you use code statements to set properties at run time iv. Write code for events After you have set the initial properties for the form and its objects, you can add code that runs in response to events. Events occur when different actions are performed on a control or object v. Save the project Save the project giving it a unique and description name. You should save the project frequently as you add code to it vi. Test and debug the application As you add code to the project, you can run the application and view its behaviour .VB also offers numerous tools for debugging your application. vii. Make an executable file Upon the completion of the project you will create an executable file. This combines the various files making up the program into a stand-alone executable file. viii. Create a set up application In order to run your application, the user usually needs other files such as DLL files or custom controls OCX files you used to create your application. VB provides the package and deployment wizard which automates the creation of the set up program and ensures the user has all necessary files. VISUAL BASIC TERMINOLOGIES Some of the common terms used in development environment are; Forms Its a window that can be customized to serve as the interface for an application or a dialogue box used to gather information to the application. Controls Prepared By Fred Lisalitsa @computer Studies Department 3

Its graphic representation of objects such as buttons, list boxes used to manipulate to provide information to the application Properties Its data that describes an object. They are characteristics of an object such as color, caption or size. Objects Its a general term used to describe all forms or controls that make up a program.VB objects have properties, methods and events. Methods. Its the actions that an object can perform or that can be performed on the object i.e. the things you can tell the object to do Events Its actions recognized by a form or control. Events occur as the use of the operating system or application interacts with the objects of a program i.e. events are the things the object does Design time This describes any time an application is being developed in the VB environment. At this time controls are added to the form and the code for the different events the control will respond to Run time Its any time the application is running VISUAL BASIC FILE TYPES A VB project is made up of the forms, modules, active X controls and environment settings that an application requires .VB maintains a project file with extension vbp .In addition to project file, a project can include the following files; 1) Form files These files contain the form, the objects on the form and code that runs when an event occurs on that form. The file extension FRM or FRX 2) VB standard module extension (BAS) These modules contains sub and function procedures that can be called by any form or object on a form. Standard modules are optional 3) Active X controls file extension( OCX) Active x controls are available from Microsoft and third party vendors. They are added using the components command on the project menu 4) VB class modules extensions (CLS) The modules contains the class definition methods and properties class modules are optional 5) Resource files extensions (RES) This file contains binary information used by the application. Resource files are typically used when creating programs for multiple languages. 6) User control extensions( CFL and CFX) These files contain source code and binary information for use in controls. These files are compiled into Active X Controls (.OCX files) 7) Upper document extension (DOBand DOX) These files contain base form and binary information for creating Active X Documents 8) Active designers extensions These files contain information about designers that are used in the project.e.g you can create a data environment for run-time data access

DATA TYPES (VARIABLE TYPES)


Variables in VB are declared using Dim statements. Though you dont have to declare variable before you first use them, its good practice to declare variables as this helps to prevent errors and allow your computer to work more efficiently. The rules for variable names are; Prepared By Fred Lisalitsa @computer Studies Department 4

a) They must begin with a letter, b) They may contain any mixture of letters and numbers, c) They may not include punctuation or symbols, with the exception of under score, d) They may not have more than forty characters. VB supports a wider range of data types (variable types) than is found on other Basics. These include; Integer This is a whole number in the range of -32,768 to +32767 Long This is a whole number in the range of -2,147,483,648 to 2,147,483,647 Single These are floating data type which holds positive or negative numbers up to around 3.4E38 Double Its a floating data type which holds positive and negative numbers to around 1.8E308 Currency This data type is called scaled integer because it deals with a fixed point numbers that have 5 digits to the left of the decimal and 4 digits to the right. This is more accurate than floating point numbers for currency values. Date It holds dates for january1, 100 to december31, 9999.Time information is also stored. Byte This data type holds positive numbers from 0 to 255 Boolean This is a simple data type that holds two values either True or False String This is a sequence of up to two billion characters Variant Its a highly flexible form of storage that takes string or number values. The nature of the variable can change during the programs run. Object The object data type stores VB objects. These can also be automation object from other applications CONVERTING BETWEEN DATA TYPES. VB supports a number of ways of converting from one type of variable to another. The following table illustrates conversion statements To do this, ANSI value to string String to lower case or upper case Date to serial number Decimal number to other bases Number to string Date to day, month, weekday or year Time to hour, minute, or second String to ASCII value String to number Time to serial number One data type to another
Prepared By Fred Lisalitsa

Use this chr Format, L case, U case Dateserial, datevalue Hex, Oct Format, str Day, month, weekday ,year Hour, minute, second ASC Val Time serial, time value CBOOL,BYTE, CCUR, CDATE, CDBI, CDEC, 5
@computer Studies Department

CINT, CLNG, CSNG, CSTR, CVAR, CRERR, FIX,INT. . SETTING VARIABLE SCOPE There are three levels of variable scope in VB as follows; a) Variables declared in the procedures as private to the procedure b) Variables declared at the form or module level in the form or modules (general) section using Dim, ReDim,Private, Static or Type area form or module-level variables. These variables are available through out the module. c) Variables declared at the module level in the modules(general)section using public as global and are available through out the project in all forms and modules .NB; you cannot use PUBLIC in procedures. HANDLING STRINGS There are two types of strings available in VB namely; Variable length strings, Fixed length strings Variable length strings can contain up to approximately two billion characters and can grow or shrink to match the data you place to it e.g. Dim Named as String Fixed length string as declared with an asterisk character (*) followed by the strings length eg. Dim Address as String*20 The address will contain 20 characters. The table below gives a list of string functions; To do this Compare two strings Convert to lower case or upper case Find length of string Justify a string Manipulate strings Use this Str comp Lcase, Ucase Len Lset, Rset Instr, left, LTRIM, MID, right, RTRIM, TRIM

DATA TYPES
Declaring constants You declare constants in VB with the CONST statement; {PUBLIC/PRIVATE} const constname [AS TYPE]=EXPRESSION The public keyword is used at the module level to make a constant global. This keyword is not allowed in procedures. The private keyword is used at module or form level to declare constants that are private which means only available within the module or form where the declaration is made. Private is not allowed in procedures The constant name identifier is the actual name of the constant. Type identifier is the data type which might be Boolean, byte, integer long, currency, single, double, date, string, or variant. The expression identifier holds the value you want for this constant. Example, Private Sub COMMAND-Click ( ) CONST PI=3.14159 Declaring variables
Prepared By Fred Lisalitsa

@computer Studies Department

Before using variables, you have to set a side memory space for item. Usually you use the Dim statement to declare variables although you can use PRIVATE, PUBLIC, STATIC (Declaring a variable that holds its value between procedure calls) REDIM (Redimension a dynamic away) or TYPE (Declare a user defined type) key words to declare variables. THE DIM STATEMENT Dim {with events} varname{([subscripts] )] [AS[NEW]type]C. [WITH EVENTS]varname [([Subscripts])] [AS[NEW]type] ]. The with events keyword is used only in class as modules. This keyword specifies that the varname is an object variable used to respond to events triggered by an active X object The varname identifier is the name of the variable you are declaring. Use subscript if you are declaring an array The new keyword enables creation of an object. Type argument specifies the data type of the variable e.g. byte if you dont specify any type then its variant. Examples DIM emploid AS integer DIM name AS string NB : 1) Static keyword can be used instead of Dim in a procedure if you want the variable to retain its value when the procedure ends. 2) Re Dim keyword can be used to set up arrays if you want to be able to change the size of the array during execution of the program LOGICAL TESTING Logical testing may be performed upon string or numeric expression or upon controls. The expression string or numeric may contain variables, literal values, functions and arithmetics or other operations as long as the expression produces values. A test will result in true, false, or null value. Null occurs when one or more of the expressions being tested has a null value. COMPARISON OPERATORS VB supports the usual set of relational or comparison operators, plus two unique to the language. 1. = = equal to 2. < > not equal to 3. < less than 4. > greater than 5. Z = =less than or equal to 6. > = greater than or equal to 7. LIKE- fuzzy string comparisons 8. IS- compares control values ARITHMETIC OPERATORS The following is the list of arithmetic operators supported by VB in order of precedence 1. Exponentiation ^ 2. Negation 3. Multiplication and Division * / 4. Integer division / 5. Modules arithmetic MOD 6. Addition and Subtraction + 7. String concatenation & LOGICAL OPERATORS
Prepared By Fred Lisalitsa

@computer Studies Department

There are six logical operators, which are mainly used to combine two or more relational operations in a test .These include 1. NOT its used with a single expression to reverse its value so that true becomes false and vise versa e.g.NOT(X>1000). 2. AND it links two expressions and is true if both expressions are true e.g X.>1000 AND Y>1000 3. OR its true if either or both expressions are true e.g. .T.>100 OR K<9000. 4. XOR (EXCLUSIVE OR) its true if one or either but not both expressions is true e.g. X>1000 X OR Y> 1000 5. EQU(EQUIVALENT) its true if both expressions are true or both are false.e.g X>1000 EQU Y>1000 6. IMP (IMPLICATIONS) Its true if both are same, as EQU,or if only the second is true . Its false only when the first expression is true and the second is false

INPUT AND OUTPUT


VB contains controls which can be used for input and output. These controls are available on tool box and the rest can be included if need be (This will be dealt with later).VB provides two functions which can be used to input or output data in a program. These functions are; THE MSGBOX( ) THE INPUTBOX ( ) 1. The msgbox This function is used to display a message to the user and get a return value corresponding to one of the buttons in the message box syntax MSGBOX (PROMPT [BUTTONS][TITLE][HELP FILE. CONTEXT]) The prompt argument holds the strings displayed as the message in the dialogue box. The buttons argument specifies what to put in the message box a specified in the table below. If the buttons are not specified, the default button is 0 or ok The title parameter holds the strings displayed in the title bar of the dialogue box Msg box function can be used to out put a value from the memory e.g. MSGBOX (the answer of the sum is$ N) N is a memory variable e.g. MSGBOX(prompt the user,64, meaningful title) CONSTANT 1. VB ok only 2. VB ok cancel 3. VB Abort retry/ ignore 4. VBYes NO 5. VB Yes No cancel 6. VB Retry cancel 7. VB Critical 8. VB exclamation 9. VB Question 10. VBApplication modal VALUE 0 1 2 4 3 5 16 48 32 0 DESCRIPTION Display ok button only Displays ok and cancel buttons Displays abort, retry, and ignore buttons Displays yes and no Displays yes, no and cancel Displays retry and cancel Displays critical message icon Displays warning message icon Displays warning query icon Application modal; The user must respond to the message before continuing work in the current application
@computer Studies Department

Prepared By Fred Lisalitsa

11. VB System modal

4696

System modal; All applications are suspended until the user responds to the message box.

The following values will be returned by the function showing which button was clicked if more than one button is displayed in the dialogue box. VALUE BUTTON 1 Ok 2 Cancel 3 Abort 4 Cancel 5 Ignore 6 Yes 7 No Example using button numbers; Dim type code as integer Dim reply as integer Typecode =32 *4 Reply=msgbox (reply quit?, type code, quit) If reply = 6, then END. 2. The input box ( ) function Its used to get a string of text from the user. It takes the following syntax Varname =INPUT (PROMPT.[TITLE][,DEFAULT][,X POS][Y POS]) Varname is the name of the variable declared using dim Prompt is the string displayed as the message in the dialogue box Title argument is the string displayed in the title bar of the dialogue box The default argument is a string displayed in the text box a the default response if no other input is provided Xpos argument is a number that specifies (in twips) the horizontal distance of the left edge of the dialogue box from the left edge of the screen Ypos argument is a number that specifies (in twips) the vertical distance of the upper edge of the dialogue box from the top of the screen The input box will always display ok and cancel and cannot hold symbols. Clicking at cancel will always cause problems. This can be corrected by use of default value and variant data type.

SELECTION
IF. .THEN. ELSE STATEMENTS This is used as branching statement. It allows the user to branch one part of the statement leaving the other part unexecuted. Syntax IF condition then Statements [Elseif condition then [Elseifstatements] ] [Else [ Elsesestatements] ] Endif Example DIM A AS LONG, B AS LONG
Prepared By Fred Lisalitsa

@computer Studies Department

A = Input box (Enter A) B = Input box (Enter the value of B) A = Val (A) B = Val (B) IF A >B then MSGBOX (The greater number is & A) Elseif B > A then MSGBOX (The greater number is & B) ELSE MSGBOX (They are equal) ENDIF NB;IF statement can be used in conjunction with logical operators to test for more than one condition. THE SELECT CASE STATEMENT This statement is used like if statement. Select statement causes a particular group of statement to be chosen from several available groups. The selection is based upon the current value of an expression which is included within the select statement. To avoid a lot of if statements use select, this will shorten the code general expression. SELECT CASE test Expression Case expression l Statements 1 Case expression 2 Statements 2 . .. Case expression n Statements n CASE ELSE [Else statements END SELECT Examples; a. SELECT CASE SUMtYPE CASE + Z =X+Y CASE - Z =X-Y CASE * Z =X*Y CASE / Z =X/Y END SELECT b. SELECT CASE COLOR CASE IS =RED MSGBOX (COLOUR IS RED) CASE IS =BLUE MGBOX (COLUR IS BLUE) CASE ELSE MSGBOX (COLOUR IS WHITE) END SELECT c. SELECT CASE MARKS Prepared By Fred Lisalitsa

10

@computer Studies Department

CASE 0 TO 39 MSGBOX (Fail) CASE 40 TO 59 MSGBOX (Pass) CASE 60 TO 79 MSGBOX (Credit) CASE ELSE MSGBOX (Distinction) END SELECT

REPETITIONS (LOOPING)
The programs that we have developed used either a sequential or a decision control statement i.e. execution was carried out in a fixed order or depending upon the outcome of a condition being tested(logical decision being taken). These programs were of limited nature because when executed they always performed the same series of actions in the same way and exactly once. Programming requires frequent performance of an action over and over, often with variations in the details each time. The mechanism that meets this is the use loops. The versatility of the computer lies in its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program either a specific number of times or until a particular condition is satisfied. The repetitive operation is done by the use of a loop control structure. GO TO STATEMENT This statement is used together with a label to branch another part of the program. It may be used with if statement to jump outside the loop. Example DIM X as integer X=0 Startloop: This is a label X =X+1 IF X = 10 then GO TO endloop Another label GO TO startloop Endloop MSGBOX Done End 1. THE FOR . . NEXT STATEMENT This is a repeating statement used to execute a statement(s) a specified number of times. Syntax For index = start to end [step step] [Statements] [Exit for] [Statements] Next index Example adding ten numbers DIM i, s, A AS integer S=0 FOR i =1 to 10 A = Input box (enter a number) S = S+A Next i MSGBOX (The total is and S )
Prepared By Fred Lisalitsa

11

@computer Studies Department

1. THE DO LOOP STATEMENT Its a repeating statement used to execute a group of statements until or while a condition is true. The condition can be evaluated at the beginning or at the end. At the beginning; DO [WHILE/UNTIL] Condition [Statements] [Exit do] [Statements] Loop At the end At the end DO [Statements] [Exit Do] [Statements] Loop [WHILE/ UNTIL] Condition Example Private sub numbers ( ) DIM X, Y AS INTEGER Y =1 S =0 DO X = INPUT BOX (ENTER NUMBER) Y =Y+1 S =S+X UNTIL Y=10 MSGBOX (Your total is & S) End sub 2. THE WHILE LOOP Its a repetition statement used if you want to stop looping when a condition is no longer true. Syntax While condition [Statements] Wend Example Dim intinput Intinput =-1 While intinput <0 Intinput =input box (enter a positive number) Wend

Prepared By Fred Lisalitsa

12

@computer Studies Department

ARRAYS
VB supports arrays where one variable is used to hold a block of data. Arrays provide a compact and efficient means of handling block of data. Arrays add power of programming than any other feature. An array is a set of variables of any type all with the same name but with different identifying numbers or subscripts. Declaring arrays You can use dim statements for standard arrays, redim for dynamic arrays, static for arrays that dont change when between calls to the procedure they are in. private for arrays private to the form or module they are declared in public or type for any array of user defined types to dimension arrays. Standard arrays Use dim statement to declare a standard array (note that in VB, arrays can have up to 60 dimensions) DIM varname [subscripts] [AS [NEW] TYPE] Varname is an identifier or name associated with the array (the name of the array) (variable name) Subscripts I used to declare the array New is keyword which enables creation of an object Type argument specifies the data type of the variable which may be byte, Boolean, integer, long, currency, single, double, date, string Examples I. Dim results (50)as integer This creates a one dimensional array of 51 integers numbered from 0 to 50. Note subscripts numbering starts from 0 unless you specify otherwise. II. Dim employees (1200)as string This will hold 200 text items. Note subscripts will start from 1 III. Dim two array (20, 40)as integer This is a two dimensional array holding a table of 20 by 40 IV. Dim marks (10,30,25)as double This is a multidimensional array holding data in three dimensions. V. Dim data et (1to15,-20 to 20)as long This creates a two dimensional array with elements running from data set (*1,-20) through to data set (15, 20) Dynamic arrays You can use the dim statement to declare an array with empty parentheses to declare a dynamic array. Dynamic arrays can be dimensioned or redimensioned as you need them with the redim statement. REDIM [PRESERVE] VARNAME (SUBSCRIPTS) [AS TYPE] Preserve key word is used to preserve the data in an existing array when you change the size of the lat dimension Varname argument hold the name of the array to (n) dimensions Subscripts term specifies the dimensions of the array Type argument specifies the type of the array. Example Dim dynastring ( ) as string Redim dynastring (10) Dynastring (1) =this is first string Redim preserve dynastring (100) Dynastring (50) =the fiftieth string
Prepared By Fred Lisalitsa

13

@computer Studies Department

USER DEFINED DATA TYPE


They are a group of variables referred to as one. In VB user defined data type are simple to declare as use. PRIVATE/PUBLIC Varname 1 AS type Varname 2 AS type . End type Use private if you want the user defined data type to be used within the form or module. Use private if you want the user defined data type to be a variable in the whole project. Type name is the variable name for the user defined data type. Varname, 2 are the individual variables within the user type. Type[e refers to the type of variable in use for each variable name. this can be byte, long, integer, double, single, currency, string, or Boolean. Example, Private type customer Name as string Address as string Adm no as long End type Individual elements can be referred to by specifying the type name followed by a dot, the variable name of the element after declaring it with the dim statement just like any other data type. Example Dim custrar as customer Custrar .name =Jones Custrar.adm no = input box (enter the admission number) You can use the with structure to avoid repetition of the data type name. e.g. With custrar Name = kamau Adm no =14897 Address =p.o box 4284 nrb End with. You can also declare user defined data type as an array. Example Dim custrar (20) as customer You can access each element by specifying the position of each record in the array. Example Custrar (1). Name =Waweru kanja Custrar (1). Adm no =14928

SUB PROGRAMMING IN VB
PROCEDURES / ROUTINE When you double click a button on a form to open its click event in the code editor, you will have noticed that the code begins and ends like this; private sub . End sub. Sub is short for subroutines. You ca n also use your own subroutines from scratch. Subroutines can be thought of as blocks of code that can organize your code into single sections to make programming easier. This is how you can declare a subroutine from scratch; [PRIVATE/PUBLIC][TATIC] UBNAME [(ARGLIST)] [Statements]
Prepared By Fred Lisalitsa

14

@computer Studies Department

[Exit sub] . [Statements] .. End sub Public keyword makes a procedure accessible to all other procedures in all modules and form Private keyword makes a procedure accessible only to other modules in the module or form in which it is declared Static specifies that the procedure local variables should be preserved between calls. Name identifier is the name of the procedure Arglist identifier is a list of parameters Statements identifier is the group of statements to be executed within the procedure. The arglist identifier has the following syntax; [BYVAL / BYREF] [PARAM ARRAY] VARNAME [( )] [AS TYPE] In arglist Byval means that the argument is passed by value Byref means that the argument is passed by reference (byref is the default in VB) Param array is used as the last argument in arglist to indicate that the final argument is an array of variant Varname is the name of the variable passed as an argument Type is the data type of the argument Finally, Exit sub keyword cause immediate exit from sub procedure and end sub ends the procedures definition. NB: When you use byval, you pass a copy of variable to a procedure. When you use byref, you pass a reference to the variable If you make changes to that reference, the original variable is changed FUNCTIONS A function is a procedure which returns a single value to its reference point. It can also be referred to as block of code that you call and pass arguments to and using functions helps break your code up into manageable parts. The function is declared using the following syntax; [PRIVATE/PUBLIC] [STATIC] FUNCTION NAME [(ARGLIT)] [AS TYPE].. [Statements] .. [Name = expression] [Exit function] [Statements] .. End function The public keyword makes the function accessible to all other procedures in all modules to form The private keyword makes a procedure accessible only to other procedures in the module or form in which it is declared Static specifies that the procedures local variables should be preserved between calls Name identifier is the name of the function. Arglist identifier I a lit of parameters Statements I a group of statement to be executed within the procedure. Prepared By Fred Lisalitsa @computer Studies Department 15

The arglist identifier has the following syntax; [OPTIONAL] [BYVAL/BYREF] [PARAM ARRAY] VARNAME [( )] [AS TYPE] [=DEFAULT VALUE] Explanation; Optional means that an argument is not required Byval means that the argument is passed by value Byref means that the argument is passed by reference. (byref is the default in VB) Param array is used as the last argument in arglist to indicate that the final argument is an array of variant elements Varname is the name of the variable passed as an argument Type is the data type of the argument Default value is any constant or constant expression, which is used as the argument default if you have used the optional keyword The type identifier I the data type returned by the function The exit function causes an immediate exit from a function

Prepared By Fred Lisalitsa

16

@computer Studies Department

CONTROLS
They are graphical tools used to create and or enhance functionality of an application. They are objects which can be passed onto a form and range from labels to file management utilities. The VB tool box includes several controls. Each control has properties, methods and events that you can use for specific purpose in the interface. Each control can have code attached to it though not all will have. Just as each type of controls has its own set of properties, some of which are common to all, so each also has its own set of events, and some of these are common to all. To see what kind of events are handled, place an object on the form and you double click on it. This opens the code window. Its here that you write the code to be attached to events. Each event has its own procedure or SUB and opening and closing lines of these are already written n for you. The name in the opening line is composed of names of the control and event linked by an underscore. Private at the start means that the code can only be accessed from that control or other controls on the same form Its important to note that the values stored in controls are accessible to other parts of a program and can therefore be used as alternative to variables. When the user types into a TEXT BOX, it is stored in the TEXT property. This can be used by code attached to the textbox or to any other control. e.g. lable1.caption=text 1.text. Every control has one main property and this is always the obvious one-The caption for a label and text of a text box. You do not have to specify this property when you want to read or change its value thus; Label=Text 1. There are two types of controls; Inherent Custom The tool box contains the inherent controls or standard controls. The custom controls are optional. You must add them to the tool box before you use them. Controls (Active x controls)are available for almost any function imaginable. These controls are contained in files that have extension OCX extension. Adding custom controls 1. Open a project 2. From project menu, click at components or right click at toolbox then close components 3. click the check box to the left of the name of the appropriate control 4. click ok to close the components dialogue box Removing custom controls 1. On the project menu, click components or right click at the tool bar then close components. 2. Clear the check box text to each control you want to remove 3. Click ok to close the components dialogue box Setting control properties You can set control properties at design time or at run time. Properties set at design time allow the developer to set default values in the application. You can use properties window to set controls at design time. 1. Right click a control and click at properties or left click the control or press F4 2. Type the value in the appropriate box To set properties for multiple controls 1. Click and drag the mouse over the controls you want to select or click and press ctrl and shift and click the controls. 2. Type the value in the appropriate property box
Prepared By Fred Lisalitsa

17

@computer Studies Department

One can also set control properties at run time. This allows you to programmatically control objects as the application are running. You use the following. WITH TXTNAME Alignment =VB centre Backcolor=VB blue Enabled = True Font. underline =True Font.size =17 Font name =Times new roman Height =700 Left =600 Text =It is well Tool tip text =welcome Top =70 Width =600 Visible =True END WITH COMMON CONTROLS 1. Command button They are used for setting properties to other controls and for writing one event click. They also serve as a method of selection. For selection purposes they are basically used where there is limited number of options. The choice may be ok or cancel, start or quit. The caption properly determines what text appears on the button and the name properly. To determine the name of the command always tart with CMD for command. Use $ character to create keyboard shortcut. Set the style property to graphical then set the picture property to a suitable icon or bitmap 2. Labels They are used to display text that the user does not need to edit. You can create a multiple label by setting its word wrap property to true. To select more than one label, select the first label then hold shift and continue selecting. To align them, choose align from format menu 3. Text boxes Text box is a control that is an essential part of the most VB applications. They provide a means by which one can type information at run time and it can provide information space by use of scroll bars and multiple properties. Set multiline property to true and its scroll bar property to both 4. A picture box Its the main graphics control. It can contain a picture created by paint or similar art packages. These must be in an acceptable format.i.e BMP, WMF, JPG OR GIF. The drawing methods can also be used in a picture box. You can load a picture in the code e.g SET 1 5. Check boxes They are ideal when you want to present a set of options from which the user can choose none, one, or more than one. A check box has a toggle switches turning options on or off. When a user clicks the box a mark appears, another click removes the mark. Examples click /AB NOTES 6. Option button They are normally used to select one from a set of mutually exclusive options. At any one time, there can only be one set on a form unless they are enclosed in frames. With option button unlike check boxes, you can only have one button checked. Checking option button automatically, uncheck any other.e.g check LAB NOTES.
Prepared By Fred Lisalitsa

18

@computer Studies Department

7. Frames Its like a decorative control used to hold other controls together. I.e. its used as a container for grouping objects together such as options buttons. 8. Images Image boxes can be used like picture box. A picture box has all the features of an image control or more. Picture boxes uses much more memory and system resources compared to image box. You cannot use an image control as a container for other controls nor can you draw graphics or text on it in your code. 9. Timer Its a control that will file an event at intervals set by the user. A timer is unusual in that its fixed in size and is invisible once the program is running. Its purpose is to control actions that must take place at or after the set intervals. You could use one to set a time limit for a response to a question to produce a ticking clock or to animate images. 10. List box Its a powerful VB control used to present a list of options/ choices to the user. If the list is too long to fit in the box, vertical scroll bars will be added at run time. Items can only be added to the list during run time. It can also be used to present information to the user. A list box can even present thousands of choices like addresses. 11. Combo box Its a one line text box combined with a list box. It can also be thought to be a combination of a drop down list with a slot in which the user can enter their own data when the program is running. The advantage of a combo box over a text box is that most choices can be presented without any need of typing them. Another advantage is that it uses less space. 12. Control collections VB provides an array that contains all control in a form. This array is known as control collections. The control collection has one property count which returns the number of controls on the form. You can use control collection to perform an action on a group of controls. Example; to clear all text boxes in a form. DIM CTL AS control. For each ctl in controls. if type name (ctl) =text box then ctl.text= end if next ctl 13. Control arrays Its a group of controls that share the same name type and event procedures. A control array has at least one element with an index property that is greater than or equal to zero. The index can grow to maximum of 32,767 elements if your system resources permit. Advantages Control arrays allow you to add new controls at run time Each new element you add to a control array inherits the common events procedures of the array. This can facilitate development Controls in a control array can share code. Creating control array at design time This can be done in three ways; 1. Give two controls the same name 2. Copy and paste a control 3. Set the index property by using the properties window. You refer to a control with the following syntax control name (Index). You specify the index of a control when you crate it. Example

Prepared By Fred Lisalitsa

19

@computer Studies Department

If chk dept (index).value =Vbchecked then SELECT CASE index CASE 0 MSG BOX (computer) CASE 1 MSG BOX (electrical) CASE 2 MSG BOX (business) End select End if. Creating controls at run time VB lets you create controls at run time. This gives you the flexibility to customize the interface according to the needs of the user. The load statement and add method are used to create controls dynamically. If you try to load a control that already exists a run time will occur. The following code creates a new control: Dim 1 as integer i = TXTarry (@).count finds the next available index Load TXT array (i) add annex text box TXTarray (i).top = TXT array (i-1).top+400 position the text box on the form TXT array (i).visible=true makes it visible You can dynamically remove controls using unload statement. If you try to unload a control that was created at design time or that has already been unloaded a run time error occurs Adding controls using the add method Private sub form _load( ) Frm students. Controls. Add VB.text box,TXT NAME WITH frm students! TXT NAME Visible = true Width = 2000 Left =1000 Top =3000 Text =home at last End with End sub.

MANAGING FORMS
Forms are the basic elements of the user interface in VB applications. They provide a frame work you can use through out your application to give a consistence look and feel. Forms serve as a window that you customize to design the interface of your applications User interface design principles The user interface is the link between your audience and the capabilities of your application. The following points should be considered when deigning a user interface such as a form Composition Its the layout or look and feel of an application. Composition includes such factors as; I. Simplicity An application must be as simple as possible for the user to understand. II. Positioning of controls Important or frequently accessed controls should be given a position of prominence. Les important controls should be neglected to less prominent locations III. Consistence
Prepared By Fred Lisalitsa

20

@computer Studies Department

Consistency or sameness is a key consideration in user interface design keeping as similar design or crock throughout your application enhances usability. IV. Affordances Affordances are visual clues to the function of user interface. User interface also makes use of affordances e.g. flat buttons might be appropriate in some cases such as in games V. White space Including white pace in your user interface can help to emphasize elements and improve usability. White space doesnt necessary have to be white; it refers to the use of blank space between and around controls on a form. VI. Color The use of color in your interface can add visual appeal but color can easily be a problem if not carefully considered on your initial design VII. Images and icons. Use of images and icons add visual interest to your application. Images can convey information efficiently without the need for text but images are often perceived differently by different people. So, consider the cultural significance of images. VIII. Fonts They are important part of your interface. They often communicate important information to the user/ choose one or two simple fonts as Arial or times new roman. IX. Menus Proper planning and design of menus and tool bars ensures that the users will understand the purpose and features of your applications. Adding a form to a project On the project menu, click at add form. The add form dialogue box appears Click at form and then click open Setting the startup form VB uses the first form in a project as the default startup form. However, as you add more new forms to the project, you may need to change this default. This can be done by; On the project menu, click at project name properties. The project properties dialogue box appears. In the startup object drop down list box, click the name of the form you want to set as the default form and click at ok. FORM METHODS A method is something that an object does. They actions that an object can perform. i. Load The load statement initializes and loads the form into memory without displaying the form on the users screen.e.g LOAD Frm my form ii. Unload Unload statement removes a form from the memory. The me statement can be used to refer to the current form in the code.e.g unload Frm my form or unload me iii. Hide Hide method removes the form from the screen without removing in from the memory. E.g. Frmmyform .hide or Me. Hide

iv. Show The show method includes an implied load. This means the specified form is not already loaded when the show method is called visual basic automatically loads ice form into memory & then displays form either modally or modeless. A modal method requires the user to take action before focus can change to another form .A modal window does not require user, action before the focus can change to another form. Prepared By Fred Lisalitsa @computer Studies Department 21

FORM EVENTS. Forms are code modules that control procedures called events. Events respond to system or user input by running whatever code you have placed in the particular events...Click events for example runs whenever the mouse is clicked to the form. When the event is called to execute its code, the required is often referred to as firing or triggering the event. These events include the following 1. Initialize. Is typically used to prepare an application for used variables are assigned to initial values and controls may be more or resized to accommodate initialization, data initialize event will fire only once during the life of application. Example Frmmyform, show Load frmmyform. Form variables can be defined in this event. Form-level variables are variables that are recognized by all procedures within that form modules. 2 load. The load events are used to perform actions that need to occur. Prior to the form being displayed it is used to assign default values to the form & its controls. The load event occurs each time that form is loaded into the memory. The load fires when a form starts as a result of the load statement show statements or when reference is made to unload form properties, methods or controls. Example PRIVATE SUB FORM-LOAD () Combol. Add item computer Combol. Add item Electrical Combol.listindex =2 End sub 3. Activate /Deactivate When the user moves between two or more forms, you can use activate and deactivate events to define the forms behavior. The activate events fires when the forms receives focus from another form within the same project and when the form is visible. Deactivate fires when a form looses focus to another form. This event fires after the lost focus event. 4 query unload Its useful when you need to know how the user is closing the form. The query unload event occurs before the form unload event. Query unload has additional features compared to the unload event. Some of the things that may cause query unload event are; the user chooses the close command from the control menu on the form the unload statement is invoked from code current operating system is ending Microsoft windows task manager is closing the application The MDI child form is closing because the MDI form is closing. To stop unloading set the cancel argument to true. Example; Private sub query unload (cancel as integer, unloadmode as integer) If unload mode < >VB form code then MSGBOX (USE TO EXIT BUTTON TO CLOSE THE FORM) Cancel = true Endif End sub 5. unload
Prepared By Fred Lisalitsa

22

@computer Studies Department

The unload event occurs before terminate events. Use the unload event procedure to verify that the form should be unloaded or to specify the actions that take place when unloading the form 6 terminate Fires when all references to an instance of a form are removed from a memory. To remove the forms variable from memory and free the form off system resources set the form equal to nothing. Set frmmyform = nothing ADDING TOOL BARS TO FORMS You can add tool bars to already existing program; just follow these steps: 1. Use the project/ components to open the components box and select the controls. 2. Click the Microsoft windows common control box and click on ok to close the component box. 3. Double click the new tool bar in the tool box to add a new tool bar to your form now. 4. Right click the tool bar now and select the properties in the pop up menu that appears opening the buttons properties page. 5. Click the buttons tab in the property page now and click insert to insert a new button into the tool bar. 6. Give the new button the caption you want and set its key property to string of text you want to refer to the button with code.7 7. Add other buttons in the same way and close the property page. 8. double click button in tool now to open code window displaying toolbar1_button click() 9. add the code you want to toolbar1_button click() by use of SELECT CASE . EXAMPLE Private sub toolbar1_button click (by Val button as cmd1.button) SELECT CASE button Key CASE FIRST MSGBOX you clicked the first button . CASE SECOND. MSGBOX you clicked the second button END SELECT END SUB. M D I (MULTIPLE DOCUMENT INTERFACE) M d I application presents the use with a single form that can contain, display arrange and manage forms inside it. The container forms are called MDI child forms. Creating MDI application is easy you simply create a standard EXE project and add a new MDI form HPM in the project menu. NB: You can arrange the MDI child forms with the MDI form method Arrange (). Example Private sub Arrange1-click me. Arrange VB cascade End sub. Other methods include VBtilehorizontal VBtilehorizontal VBarrangeicons
Prepared By Fred Lisalitsa

23

@computer Studies Department

ADDING A MENU TO A FORM You can add a menu to a form by using visual basic menu editor. To add a menu to a form select that form and open the menu editor by selecting the menu editor in the tools menu. Here is how to create anew menu system in menu editor step by step. 1. enter the first menus caption and name 2. click the next button or press enter 3. click the right arrow to indent one level making this next entry a menu item 4. enter the items caption and name 5. click the next button 6. repeat steps 4&5 for all items in the first menu 7. click the next button 8. click the left arrow to outdent making this next entry menu 9. enter the next menus caption and name 10. click the right arrow to indent one level making this next entry a menu item 11. repeat steps 4&5 for the items in this new menu 12. repeat step 7 through all for the rest of the menus in the program 13. click on ok to close the menu editor 14. edit the code NB: You can add main separator by choosing it on the editor menu and a short cut key by also selecting on the editor menu CREATING POPUP MENUS Pop up menus are those menus that appear when you right click a form. To create a new pop up menu just user the menu to create a new menu named pop up. Note that we set this menus visible properly false too make sure we dont display it in the menu bar. You can code the action the same way as the normal menus.

VALIDITION
Data validation ensures that every data value entered into your application is accurate and of a valid data type. Verifying the data type is one of the most common tasks in data validation. A well designed application can prevent most data-entry errors. Setting up your application to accept the proper information from the calculations and can even prevent run time errors such as type mismatch . Types of validation 1. form-level validation Form level validation verifies data after all fields on a form have been completely filled in by a user. 2. field-level validation Field level validation verifies the data in each field one at a time as each field is filled. FORM-LEVEL VALIDATION When you use form level validation, you verify the data in each field on a form in a single procedure. You can have a ok button which can be used to verify that all text boxes has data before a certain action is taken e.g. update fields in a table. The following code in a click event us used to make sure that all the text boxes have data. Private Sub Command1_Click() Dim ELEMENT As Control For Each ELEMENT In Controls Prepared By Fred Lisalitsa
@computer Studies Department

24

If TypeOf ELEMENT Is TextBox Then If ELEMENT.Text = "" Then MsgBox ("All Text Boxes Require Data") Exit Sub End If End If Next ELEMENT End Sub FIELD-LEVEL VALIDATION You may want to validate data as it is entered into each field. Field level validation provides immediate direction to the user and gives the developer control over user actions. This can be done in various ways; 1. Using the text box control properties The textbox control contains several design type properties that restrict the type of values user can enter. These properties include the following: Maxlength property:- this is used to set the maximum number of characters that the user can enter into a textbox Password char property: - the password character property lets you hide (or mask) characters that are entered into a textbox. Lock property:- the locked property setting determines whether a user can edit the text in a text box. If locked property is set to true the user can view the text in the text box but cannot edit the text 2. Using events Validating change events-a text box controls fires a change event each time the user enters a character into text box Using the validate event- the simplest way to validate data is to use the validate event. The validate event also provides you with control over when focus can be moved to another control. Using validate event you can prevent the focus from even shifting top another control until all validation rules have been met. PRIVATE SUB TXTNAME- validate ( ) If Len (txt name. text) <1 then MSGBOX You must type name CANCEL =True Endif End sub Or If Len (txt state. text) < > 2 then MSGBOX State must be two characters Cancel = True Endif 3 using lost focus The lost focus event occurs when an object loses focus. This can occur as a result of user action such as tabbing to another field or clicking another object. This validation technique can result in an infinite loop where one or more controls are using the set focus method in the lost focus event. 4 using key press When a user enters a standard ASCII character the key event occurs. By responding to the key press event you can restrict the characters entered or transform them as are typed. Example; Private Sub txtClientNumber_KeyPress(KeyAscii As Integer) 'This procedure ensure that you only enter numbers Select Case KeyAscii Case Asc("0") To Asc("9") Case 32, vbKeyDelete, Asc(vbBack) Prepared By Fred Lisalitsa @computer Studies Department 25

Case Else KeyAscii = 0 txtClientNumber.SetFocus txtClientNumber = "" End Select End Sub 5. Validation events VB include several functions that assist in the process. These functions include; Isnumeric Isdate Isalphabetic a) Isnumeric This function returns a value of true if the argument is numeric. If the argument is not numeric, false is returned b) Isdate This returns a value of true if the argument is a valid date. If the argument is not a valid date, false is returned. If Isnumeric (txtname .text) then, MSGBOX Name cannot be numeric TXTNAME. Set focus Cancel= true ENDIF. If is date (txtname.text) then MSGBOX Name cannot be date TXTNAME. Set focus Cancel= true ENDIF 6. MASK PROPERTY The mask property forces data to be entered in a predefined template. You can et this property at design time or at run time. Mask property can be used to validate content such as the correct month or time of the day. Example; MSKphone. Mask = (# # #) # # #. # # # The mask property is used with masked edit control. To add the masked edit control to the tool box use; On the project menu click components. The components dialogue box appears. On the controls tab, select Microsoft masked control 6.0 then click ok Clearing a masked edit You can clear a masked edit box by the following code; MSK phone number. Mask = You can use the text property after the masked edit box is empty MSK phone number. Text =

Prepared By Fred Lisalitsa

26

@computer Studies Department

ERROR HANDLING
Creating an error handler When VB encounters a run time error, it checks to see whether an error handler has been created. If it has not, VB automatically presents to the user a message box showing an error number and a brief description. If the user clicks at ok, the application is terminated. Error handlers are specific to individual procedures. This means that each event or general procedure you create should have its own error handler. There are three basic steps in creating an error handler. Enable an error handler. Add code to handle the possible errors Resume normal execution of the program To enable error handler, use on error GO TO statement and provide the names of a label in your procedure. The label marks a point in code that you want VB to jump to when a runtime error occurs. Labels follow the same naming rules a variable. However you must add a colon to the end of the name. Example; Private sub CMD open click ( ) On error GO TO openerror Code that opens a database Exit SUB Open error: code to handle an error goes here END SUB The following example shows the error that occurred; Error handler: MSGBOXThe following error occurred and Err.description When the error has been handled, the final step is to resume execution of the application. There are three ways to return control. a. Retry the line code that caused the initial error b. Start from the line immediately following the one that caused the error c. Terminate the application This can be done by the following code. DIM ANS AS INTEGER Error handler: ANS =MSGBOX (An error occurred, VBAbortRetryIgnore) SELECT CASE ANS CASE VBRETRY RESUME CASE VBIGNORE RESUME NEXT CASE VBABORT UNLOAD ME END SELECT Example; DIM ANS AS INTEGER My error handler: ANS =MSGBOX (An error occurred , VB abort retry ignore) SELECT CASE ANS CASE VB RETRY NUM =INPUTBOX (ENTER THE CORRECT VALUE) RESUME CASE VB IGNORE RESUME NEXT Prepared By Fred Lisalitsa @computer Studies Department 27

CASE VB ABORT UNLOAD ME END SE LECT NB; Resume line or label can be used to return to a specific line, number or label.

Prepared By Fred Lisalitsa

28

@computer Studies Department

SEQUENTIAL ACCESS FILES


Sequential files are like tape cassettesyou read data from them in a sequential manner. If you want data at the end of the file, you have to read all the intervening data first. Sequential files are often organized into text strings in Visual Basic. Here are the Visual Basic statements and functions you use with sequential files (the # symbol refers to an open file, as well see): Open Line Input # Print # Write # Input$ Input # Close

In addition, Visual Basic supports TextStream objects to make working with sequential files easier, as well see later in this chapter. Here are the major TextStream methods: Read ReadAll ReadLine Write WriteBlankLines WriteLine Close

When do you use sequential files? If youve got a text file full of variable-length strings, you usually treat that file as sequential. You can also use sequential files to store binaryformat items like numbers.

Random Access Files


If sequential files are like cassettes, random access files are more like CDs. Random files are organized into records (usually of the same length), and you can read a particular record without having to read all the intervening datayou can move to that record in a file directly, just as you can move to a CD track. Here are the Visual Basic statements and functions you use with random access files: TypeEnd Type (to create and format records) Open Put # Len Seek LOC Get # Close

Prepared By Fred Lisalitsa

29

@computer Studies Department

When do you use random access files? If you want to create your own database files, formatted as you want them, youd organize them into records. In fact, any file that you want to organize into records is best formatted as a random access file. Binary Files Binary files are simply unformatted binary data, and Visual Basic does not interpret (such as looking for text strings) or organize the contents (into records) of such files at all. These files are just bytes to Visual Basic, and the statements and functions you usually use with these files include the following: Open Get Put Seek Close

Binary files include EXE files, graphics files, and so on.

CREATING A FILE The Testing Department is on the phone again. Your new SuperDuperTextPro wordprocessing program is great, but shouldnt it offer users some way to save their text in a file? Hmm, you think, could be a good idea. So how do you create a file in Visual Basic? The standard way is to use the Open statement (well see another way when we work with TextStream objects later in this chapter). Heres how the Open statement works:
Open pathname For mode [Access access] [lock] As [#] filenumber [Len= reclength]

Here are what the various arguments mean: pathnameA file name (may include directory or folder, and drive). modeA keyword specifying the file mode: Append, Binary, Input, Output, or Random (if unspecified, the file is opened for Random access). accessA keyword specifying the operations permitted on the open file: Read, Write, or Read Write. lockA keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write. filenumberA valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number. reclengthA number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered. If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs. Also note that the Len clause is ignored if mode is Binary.
Prepared By Fred Lisalitsa

30

@computer Studies Department

So how do you create a file with Open? If the file specified by pathname doesnt exist, it is created when a file is opened for Append, Binary, Output, or Random modes. After youve created the file, you refer to it using the file number. Lets see an example. Here, well let users write the text in a text box, Text1, to a file on disk, file.txt, when they press a button. Because file operations are prone to error (we might run into missing diskettes, locked files, and so on), we start by checking for errors:
Private Sub Command1_Click() On Error GoTo FileError ... FileError: MsgBox "File Error!" End Sub

Next, we create file.txt as file #1:


Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 ... FileError: MsgBox "File Error!" End Sub

Now we write the text in Text1 to the file with the Print # method:
Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 Print #1, Text1.Text ... FileError: MsgBox "File Error!" End Sub

And finally we close the file:


Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 Print #1, Text1.Text Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

When you add a text box, Text1, to the form, and a command button, Command1, labeled Write text to file, and run the program, you see the display much like that in Figure 17.3. When you click the command button, the new file is created and written. Getting A Files Length When you start reading files in code, it can help to know the files length (for one thing, it can tell you how many bytes to read in). There are two ways to determine file length, the FileLen and the LOF functions.
Prepared By Fred Lisalitsa

31

@computer Studies Department

The FileLen Function


The FileLen function returns the length of a file (in bytes) on disk. Heres an example in which we report the size of a file, file.txt, in a message box using FileLen:
Private Sub Command1_Click() MsgBox "The file.txt file is" & Str(FileLen("c:\file.txt")) & _ " bytes long." End Sub

The LOF Function


The LOF function returns the length of a file (in bytes) opened with the Open statement. You pass the LOF function an open file number. Heres an example in which we report the length of a file weve just written, using the LOF function:
Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 Print #1, Text1.Text MsgBox "The file is" & Str(LOF(1)) & " bytes long." Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

Opening A File How do you open a file in Visual Basic? You use the Open statement. Heres how the Open statement works:
Open pathname For mode [Access reclength] access] [ lock] As [#] filenumber [Len=

Here are what the various arguments mean: pathnameA file name (may include directory or folder, and drive). modeA keyword specifying the file mode: Append, Binary, Input, Output, or Random (if unspecified, the file is opened for Random access). accessA keyword specifying the operations permitted on the open file: Read, Write, or Read Write. lockA keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write. filenumberA valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number. reclengthNumber less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered. If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and an error occurs. Also note that the Len clause is ignored if mode is Binary . If the file specified by pathname doesnt exist, it is created
Prepared By Fred Lisalitsa

32

@computer Studies Department

when a file is opened for Append, Binary, Output, or Random modes. If you open an existing file for Output, it is overwritten; if you open it for Append, new data is added to the end of the file. After youve created the file, you refer to it using the file number. For example, here we open a file named file.txt and write the contents of a text box, Text1, to that file:
Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 Print #1, Text1.Text Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

Writing To A Sequential File Sequential files are often text strings in Visual Basic, but they can also be combinations of text and numbers. You usually use these standard statements to write to sequential files in Visual Basic (well also see how to use the TextStream methods later in this chapter):
Print # number, expressionlist Write # number, expressionlist

Here, number is an open file number and expressionlist is a list of variables to write, separated by commas. Lets take a look at some examples.

The Print # Statement


If you want to store your data in text format, use Print # . As an example, well store the text in a text box to a file named file.txt using Print # . We start by checking for errors:
Private Sub Command1_Click() On Error GoTo FileError ... FileError: MsgBox "File Error!" End Sub

Then we open a file for output:


Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 ... FileError: MsgBox "File Error!" End Sub

Then we print the text in a text box, Text1, to the file:


Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 Print #1, Text1.Text

Prepared By Fred Lisalitsa

33

@computer Studies Department

... FileError: MsgBox "File Error!" End Sub

Finally we close the file:


Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 Print #1, Text1.Text Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

And thats itnow the user can write the contents of a text box out to disk. The code for this is located in the filewrite folder on this books accompanying CD-ROM.

The Write # Statement


You can also use the Write # statement to write text and other types of data to a file. You use this statement with a file number and a comma-delimited list of the variables you want to write to that file. For example, here we open a file, data.dat, and write two numbers that the user has entered in the text boxes Text1 and Text2 to that file:
Private Sub Command1_Click() Open "c:\data.dat" For Output As #1 Write #1, Val(Text1.Text), Val(Text2.Text) Close #1 End Sub

To see how to read those values back in, take a look at Reading From Sequential Files coming up in this chapter. Writing To A Random Access File You usually write records to random access files using the Put statement:
Put [#] filenumber, [recnumber ], varname

Here, filenumber is the number of a file to write to, recnumber is the number of the record to write (you set the record size when you open the file), and varname is the name of the variable that holds the data to write to the file. To work with records in a random access file, you define a record type first. For example, here we define a new type named Record in a module (you can only define types in modules; to add a new module to a program, use the Project menus Add Module item):
Type Record Name As String * 50 Number As String * 50 End Type

Note that we use fixed-length strings here to make all our records the same size. Prepared By Fred Lisalitsa @computer Studies Department 34

Now in a program, we can set up an array of such records in the (General) part of a form, as well as an integer to keep track of the total number of records:
Dim WriteData(1 To 50) As Record Dim TotalRecords As Integer

In this example, well just have one record, which we fill from the text boxes Text1 and Text2 when the user clicks a button:
Private Sub Command1_Click() WriteData(1).Name = Text1.Text WriteData(1).Number = Text2.Text TotalRecords = 1 ...

Next, we create a file to store our record(s) innote that we set the size of each record in the file with the Len keyword:
Private Sub Command1_Click() WriteData(1).Name = Text1.Text WriteData(1).Number = Text2.Text TotalRecords = 1 On Error GoTo FileError Open "c:\records.dat" For Random As #1 Len = Len(WriteData(1)) ... FileError: MsgBox "File Error!" End Sub

Finally, we use the Put statement to write the data to the file. We only have one record here, but if we had a number of records, we could loop like this:
Private Sub Command1_Click() WriteData(1).Name = Text1.Text WriteData(1).Number = Text2.Text TotalRecords = 1 On Error GoTo FileError Open "c:\records.dat" For Random As #1 Len = Len(WriteData(1)) For loop_index = 1 To TotalRecords Put #1, , WriteData(loop_index) Next loop_index Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

And thats itweve written our data file. To see how to read records back in, see Reading From Random Access Files later in this chapter. Writing To A Binary File You usually write records to binary files using the Put statement:
Prepared By Fred Lisalitsa

35

@computer Studies Department

Put [#] filenumber, [recnumber], varname

Here, filenumber is the number of a file to write to, recnumber is the number of the record to write for random files and the byte at which to start writing for binary files, and varname is the name of the variable that holds the data to write to the file. Heres an example showing how to use Put to write a floating point number the user has entered in a text box, Text1, to a filenote that we open that file in Binary mode and dont use a record number with Put here:
Private Sub Command1_Click() Dim varOutput As Double varOutput = Val(Text1.Text) On Error GoTo FileError Open "c:\binary.dat" For Binary As #1 Put #1, , varOutput Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

To see how to read the binary data back in, see Reading from Binary Files later in this chapter. Reading From Sequential Files To read from sequential file, you can use these standard statements (well see how to use TextStream methods later in this chapter):
Input # number, expressionlist Line Input # number, string Input$ ( numberbytes, [#] number)

Here, number is a file number, expressionlist is a list of variables the data will be stored in, string is a string variable to store data in, and numberbytes is the number of bytes you want to read. Lets see some examples.

The Input # Statement


You can use the Input # statement to read text and numbers from a sequential file. For example, if we write two integers the user has entered in Text1 and Text2 to a file, data.dat, this way using Write # when the user clicks Command1:
Private Sub Command1_Click() Open "c:\data.dat" For Output As #1 Write #1, Val(Text1.Text), Val(Text2.Text) Close #1 End Sub

then we can read those integers back using Input # this way when the user clicks Command2:
Private Sub Command2_Click() Dim int1, int2 As Integer

Prepared By Fred Lisalitsa

36

@computer Studies Department

Open "c:\data.dat" For Input As #1 Input #1, int1, int2 Text3.Text = Str(int1) Text4.Text = Str(int2) Close #1 End Sub

The Line Input Statement


Using the Line Input statement, you can read lines (text strings that end with a carriage return or carriage return/line feed pair) from a file. For example, say we had this set of lines, each separated by a carriage return/line feed pair in a file named file.txt:
Here is some multi-line text that we will read in...

When the user clicks a button, we can read in the preceding text line by line with Line Input . First, we open the file:
Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Input As #1 ... FileError: MsgBox "File Error!" End Sub

Now we need some way of looping over all the lines in the filebut how do we know when weve reached the end of the file? We use the Visual Basic EOF (End Of File) function, which returns True when we reach the end of the file:
Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Input As #1 Do Until EOF(1) ... Loop Exit Sub FileError: MsgBox "File Error!" End Sub

Next we use Line Input to read lines of text from the file and append them to a multiline text box (that is, a text box with its MultiLine property set to True), Text1, along with a carriage return line feed pair this way:
Private Sub Command1_Click() Dim NewLine As String On Error GoTo FileError Open "c:\file.txt" For Input As #1

Prepared By Fred Lisalitsa

37

@computer Studies Department

Do Until EOF(1) Line Input #1, NewLine Text1.Text = Text1.Text + NewLine + vbCrLf Loop Exit Sub FileError: MsgBox "File Error!" End Sub

The Input$ Statement


The Input$ statement lets you read in a string of a specified length. It might seem odd to have to know the strings lengths before reading them in, but Input$ does have one very useful aspect: if you use it together with the LOF (Length Of File) function, you can read in a whole text file at once. For example, heres how we read in the file from the previous example, file.txt, all at once, without having to work line by line:
Private Sub Command1_Click() Dim NewLine As String On Error GoTo FileError Open "c:\file.txt" For Input As #1 Text1.Text = Input$(LOF(1), #1) Exit Sub FileError: MsgBox "File Error!" End Sub

This example produces the same result as the previous example that uses Line Input. Reading From Random Access Files The Testing Department is on the phone. Your new program, SuperDuperDataCrunch, is great for writing data to disk, but shouldnt you let the user read that data back in? Hmm, you think, good idea. You use Get to read records from a random access file:
Get [#] filenumber, [recnumber], varname

Here, filenumber is the number of a file to read from, recnumber is the number of the record to read, and varname is the name of the variable that should receive the read-in data. Lets see an example. Earlier in this chapter, we saw how to write records to a random access file. We set up a new type named Record in a module:
Type Record Name As String * 50 Number As String * 50 End Type

Prepared By Fred Lisalitsa

38

@computer Studies Department

Then we set up two formwide arrays of records, WriteData and ReadData, and an integer named TotalRecords to keep track of how many records are total (these variables are stored in the (General) section of the form):
Dim WriteData(1 To 50) As Record Dim ReadData(1 To 50) As Record Dim TotalRecords As Integer

When the user clicked a command button, we read the text from two text boxes, Text1 and Text2, placed that text in the first record of the WriteData array, and wrote that record out to a file named records.dat with the Put statement:
Private Sub Command1_Click() WriteData(1).Name = Text1.Text WriteData(1).Number = Text2.Text TotalRecords = 1 On Error GoTo FileError Open "c:\records.dat" For Random As #1 Len = Len(WriteData(1)) For intLoopIndex = 1 To TotalRecords Put #1, , WriteData(intLoopIndex) Next intLoopIndex Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

Now well see how to read that record back in. First, we open the file records.dat for random access, setting the record size to the length of each array element:
Private Sub Command2_Click() Open "c:\records.dat" For Random As #1 Len = Len(ReadData(1)) ...

Then we use Get to read in the records:


Private Sub Command2_Click() Dim intLoopIndex As Integer Open "c:\records.dat" For Random As #1 Len = Len(ReadData(1)) For intLoopIndex = 1 To LOF(1) / Len(ReadData(1)) Get #1, , ReadData(intLoopIndex) Next intLoopIndex

Next, we loop over all the records in the file (although we use LOF(1) / Len(ReadData(1)) to determine the number of records in the file, we could also loop until the EOF function is True):
Private Sub Command2_Click() Dim intLoopIndex As Integer Open "c:\records.dat" For Random As #1 Len = Len(ReadData(1)) For intLoopIndex = 1 To LOF(1) / Len(ReadData(1)) ... Next intLoopIndex

Prepared By Fred Lisalitsa

39

@computer Studies Department

...

Then we close the file and display the Name and Number fields of the first (and only) record in two new text boxes, Text3 and Text4:
Private Sub Command2_Click() Dim intLoopIndex As Integer Open "c:\records.dat" For Random As #1 Len = Len(ReadData(1)) For intLoopIndex = 1 To LOF(1) / Len(ReadData(1)) Get #1, , ReadData(intLoopIndex) Next intLoopIndex Close #1 Text3.Text = ReadData(1).Name Text4.Text = ReadData(1).Number Exit Sub FileError: MsgBox "File Error!" End Sub

Reading From Binary Files How do you read raw data from files that have been opened in Binary format with the Open statement? You usually use Get to read data from a binary file (although you can use Input # as wellsee the previous topic on reading from sequential files):
Get [#] filenumber, [recnumber], varname

Here, filenumber is the number of a file to read from, recnumber is the number of the record to read for random files and the byte at which to start reading for binary files, and varname is the name of the variable that will hold the read-in data. Lets see an example. In this case, we first write some binary datasuch as a floating point numberto a file, and then well read it back in. Here, we let the user enter a Double value in a text box, which we read in when the user clicks a command button, Command1:
Private Sub Command1_Click() Dim varOutput As Double varOutput = Val(Text1.Text) ...

Then we write that number out to a binary file, binary.dat (making it a binary file by opening it in Binary mode):
Private Sub Command1_Click() Dim varOutput As Double varOutput = Val(Text1.Text) On Error GoTo FileError Open "c:\binary.dat" For Binary As #1 Put #1, , varOutput Close #1 Exit Sub

Prepared By Fred Lisalitsa

40

@computer Studies Department

FileError: MsgBox "File Error!" End Sub

Now its up to us to read that number back in as binary data when the user clicks a new button, Command2 . We start by opening the file again:
Private Sub Command2_Click() On Error GoTo FileError Open "c:\binary.dat" For Binary As #1 ... FileError: MsgBox "File Error!" End Sub

Next, we use Get to read in the number and store it in a new variable, varInput:
Private Sub Command2_Click() Dim varInput As Double On Error GoTo FileError Open "c:\binary.dat" For Binary As #1 Get #1, , varInput ... FileError: MsgBox "File Error!" End Sub

Finally, we display the newly read-in variable in a text box, Text2, and close the file:
Private Sub Command2_Click() Dim varInput As Double On Error GoTo FileError Open "c:\binary.dat" For Binary As #1 Get #1, , varInput Text2.Text = Str(varInput) Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

Accessing Any Record In A Random Access File When youve set up a file to hold records (by creating it in Random mode with the Open statement and passing the length of the records you want to open), you can use Get to access any record in the file by record number:
Get #1, recordnumber, variablename

In this case, were reading record number recordnumber from file 1 and placing the data read into a variable named variablename . In the same way, you can write any record with Put:
Put #1, recordnumber, variablename

Prepared By Fred Lisalitsa

41

@computer Studies Department

Using Get and Put in this way, you can read and write any record in the file. Closing A File How do you close a file in Visual Basic? Its simpleyou just use the Close statement: Private Sub Command1_Click() On Error GoTo FileError Open "c:\file.txt" For Output As #1 Print #1, Text1.Text Close #1 Exit Sub FileError: MsgBox "File Error!"
End Sub

Prepared By Fred Lisalitsa

42

@computer Studies Department

WORKING WITH DATABASES IN VISUAL BASIC


What, then, is a database? A database is just a collection of one or more tables. In fact, you can go farther than that in Visual Basicyou can have collections of databases. In DAO, those collections are called the workspace, and in RDO and ADO, they are referred to as the data environment. You can also have indices in databases, and those are pointers to specific fields, either in the current database or another one. How do you work with the data in that database? You use SQL to set up a query, which when applied to a database gives you a record set. This record set is made up of the records from the database that matched your queryfor example, you may have asked for all students that got a grade of B or better. There are three different ways of working with a database in Visual Basic.

DAO
When Visual Basic first started working with databases, it used the Microsoft Jet database engine, which is what Microsoft Access use. Using the Jet engine represented a considerable advance for Visual Basic, because now you could work with all kinds of data formats in the fields of a database: text, numbers, integers, longs, singles, doubles, dates, binary values, OLE objects, currency values, Boolean values, and even memo objects (up to 1.2GB of text). The Jet engine also supports SQL, which database programmers found attractive. To support the Jet database engine, Microsoft added the data control to Visual Basic, and you can use that control to open Jet database (.mdb) files. Microsoft also added a set of Data Access Objects (DAO) to Visual Basic: DBEngineThe Jet database engine WorkspaceAn area can hold one or more databases DatabaseA collection of tables TableDefThe definition of a table QueryDefThe definition of a query RecordsetThe set of records that make up the result of a query FieldA column in a table IndexAn ordered list of records RelationStored information about the specific relationship between tables

The Data Control


The data control enables you to move around in a database from record to record and to display and manipulate data from the records in bound controls. This control displays a set of arrow buttons the user can manipulate to move through a database, and the records from that database are displayed in bound controls. In fact, you can perform most data access operations using the data controlwithout writing any code. Data-bound controls automatically display data from one or more fields for the current record, and the data control performs all operations on the current record. If the data control is made to move to a different record, all bound controls automatically pass any changes to the data control to be saved in the database. The data control then moves to the requested record and passes back data from the current record to the bound controls where its displayed. When an application begins, Visual Basic uses data control properties to open a selected database, create a DAO Database object, and create a Recordset object. The data controls Database and Recordset properties refer to those Database and Recordset objects, and you can manipulate the data using those properties. For example, if you have an SQL statement
Prepared By Fred Lisalitsa

43

@computer Studies Department

to execute, you place that statement in the data controls RecordSource property, and the result appears in the Recordset property.

RDO
Remote Data Objects (RDO) connect to databases using ODBC. You set up ODBC connections to databases using the ODBC item in the Windows Control Panel, and then use one of those connections with the RDO objects. The Remote Data Objects are designed in parallel with the Data Access Objects; for example, the database engine is rdoEngine instead of DBEngine, Recordsets have become rdoResultsets, TableDefs became rdoTables, Workspaces became rdoEnvironments, Field objects became rdoColumn objects, and so on. Although the names have changed, the command set is very similar to DAO. Although Microsoft intends ADO to supercede RDO, many programmers will use RDO for some time to come

The Remote Data Control


Like the data control, the remote data control gives you access to a database and displays data in bound controls. Unlike the data control, however, you use the remote data control to access ODBC data sources (which can include databases built with all the popular commercial database programs). As with the data control, if the remote data control is instructed to move to a different row, all bound controls automatically pass any changes to the remote data control to be saved to the ODBC data source. The remote data control then moves to the requested row and passes back data from the current row to the bound controls where its displayed. In fact, the remote data control behaves like the data control in most respects, with some differences; for example, you can treat the remote data controls SQL property like the data controls RecordSource property, but it cannot accept the name of a table by itself unless you populate the rdoTables collection first.

ADO
Microsofts latest set of data access objects are the ActiveX Data Objects (ADO). These objects let you access data in a database server through any OLE DB provider. ADO is intended to give you a consistent interface for working with a wide variety of data sources, from text files to ODBC relational databases to complex groups of databases. The way Microsoft implements connections to all those data sources is with the OLE DB set of COM interfaces, but that standard is a very complex one. Our interface to that interface, so to speak, is ADO, a set of objects with properties, events, and methods. Here are the ADOs: ConnectionAccess from your application to a data source is through a connection, the environment necessary for exchanging data. The Connection object is used to specify a particular data provider and any parameters. CommandA command issued across an established connection manipulates the data source in some way. The Command object lets ADO make it easy to issue commands. RecordsetIf your command is a query that returns data as rows of information in a table, then those rows are placed in local storage in a Recordset object. FieldA row of a Recordset consists of one or more fields, which are stored in Field objects. ErrorErrors can occur when your program is not able to establish a connection, execute a command, or perform an operation, and ADO supports an Error object to hold the resulting error. EventsADO uses the concept of events, just like other interface objects in Visual Basic. You use event handling procedures with events. There are two types of events: ConnectionEvents (issued when transactions occur, when commands are executed, and
Prepared By Fred Lisalitsa

44

@computer Studies Department

when connections start or end) and RecordsetEvents (events used to report the progress of data changes). The Data-Bound Controls You can bind certain controls to the data control, the remote data control, and the ADO data control, and those controls are called bound controls. To bind a control to a database control, you use properties like DataSource to specify the database control, and then use properties like DataField or BoundColumn to specify what field to display in the bound control, as well see. Here are the controls that can function as bound controls: Picture boxes Labels Text boxes Checkboxes Image controls OLE controls List boxes Masked edit controls Combo boxes The Visual Data Manager. You can use this tool to create and modify databases. You create a new database with the File menus new item and open an existing database with the Open item. Lets see an example. Here, well create a new database with the Visual Data Manager. Click the Table Type Recordset button, which is the button at the extreme left in the toolbar, and the Use Data Control On New Form button, which is the fourth button from the left. Next, select the New item in the File menu. The Visual Data Manager lets you design databases in several different formats; for this example, choose Microsoft Access Version 7 MDB or later. The Visual Data Manager asks you for a name and path for this new database; well call it db.mdb, so enter that name now and click on OK. Creating A Table With The Visual Data Manager To add a table named students to the db.mdb database we created, right-click the Properties item in the Visual Data Managers Database window and select the New Table item, opening the Table Structure window Give this new table the name students by typing that into the Table Name field Creating A Field With The Visual Data Manager To add fields to the database table named students we created in the previous topic, click the Add Field button in the Visual Data Managers Table Structure window, opening the Add Field dialog box Give this new field the name Name by typing that into the box labeled Name and clicking on the OK button. The Add Field dialog box stays open, and the new field is added to the students table. Add another field named Grade in the same way. Click on OK to add the field, then click Close to close the Add Field dialog box. Now in the Table Structure window, click the Build The Table item to build the new table with our two new fields. This creates the students table with two fields: Name and Grade, and opens that table in the Visual Data Managers Database window, Adding A Data Control To A Program The data control is the only intrinsic database controlits already in the toolbox. This controls tool appears as the tenth tool down on the right in the toolbox. Add this control on the form set its properties Opening A Database With The Data Control To connect a data control to a database, you just set the data controls DatabaseName property to the path and name of the Access/Jet database file you want to open. Here, well Prepared By Fred Lisalitsa @computer Studies Department 45

use the db.mdb file weve created at the beginning of this chapter. In addition, you select the table you want to work with in that file with the data controls RecordSource property. After connecting the control to the db.mdb database, select the students table in the dropdown list box for the RecordSource property in the Properties window. Connecting A Data Control To A Bound Control To connect a text box to a data control, set the text boxs DataSource property to the name of the data control (or remote data control or ADO control). To display a particular field in the text box, place that fields name in the text boxs DataField property. Adding Records To Databases You can add a new record to a database with the AddNew method of the Recordset property of a data or ADO data control, or of the Resultset property of a remote data control. Lets see an example. When the user clicks the Add button in the dbmethods example were developing in this and the previous few topics, we can add a new record like this: Private Sub cmdAdd_Click() Data1.Recordset.AddNew End Sub This adds a new, blank record. You can enter the data you want in the records fields, and to update the database, you click the Update button. Deleting Records In Databases You can delete a record in a database with the Delete method of the Recordset property of a data or an ADO data control, or of the Resultset property of a remote data control. Lets see an example. When the user clicks the Delete button in the dbmethods example were developing in this and the previous few topics, we can delete a record like this: Private Sub cmdDelete_Click() Data1.Recordset.Delete ... End Sub To avoid displaying a blank record, we also move to the next record this way: Private Sub cmdDelete_Click() Data1.Recordset.Delete Data1.Recordset.MoveNext End Sub Refreshing A Data Control When working with multiple databases, you can refresh the data in the current database control with the Refresh method of the data, ADO data control, or the remote data control. Lets see an example. When the user clicks the Refresh button in the dbmethods example were developing in this and the previous few topics, we can refresh the control like this: Private Sub cmdRefresh_Click() Data1.Refresh End Sub Updating A Database With Changes After changing the fields in a record, you can update a database with the UpdateRecord method of the data, ADO data control, or remote data control. Lets see an example. When the user clicks the Update button in the dbmethods example were developing in this and the previous few topics, we can update the database with the new record like this: Private Sub cmdUpdate_Click() Data1.UpdateRecord End Sub Moving To The Next Record
Prepared By Fred Lisalitsa

46

@computer Studies Department

You can move to the next record of a database with the MoveNext method of the Recordset property of a data or ADO data control, or of the Resultset property of a remote data control. Lets see an example. When the user clicks the Next button in the dbmethods example were developing in this and the previous few topics, we can move to the next record like this: Private Sub cmdNext_Click() Data1.Recordset.MoveNext End Sub Moving To The Previous Record You can move to the previous record of a database with the MovePrevious method of the Recordset property of a data or ADO data control, or of the Resultset property of a remote data control. Lets see an example. When the user clicks the Previous button in the dbmethods example were developing in this and the previous few topics, we can move to the previous record like this: Private Sub cmdPrevious_Click() Data1.Recordset.MovePrevious End Sub
TIP: When you use MovePrevious, make sure you dont try to move back before the first record of the database.

Moving To The First Record You can move to the first record of a database with the MoveFirst method of the Recordset property of a data or ADO data control, or of the Resultset property of a remote data control. Lets see an example. When the user clicks the First button in the dbmethods example were developing in this and the previous few topics, we can move to the first record like this: Private Sub cmdFirst_Click() Data1.Recordset.MoveFirst End Sub Moving To The Last Record You can move to the last record of a database with the MoveLast method of the Recordset property of a data or ADO data control, or of the Resultset property of a remote data control. Lets see an example. When the user clicks the Last button in the dbmethods example were developing in this and the previous few topics, we can move to the last record like this: Private Sub cmdLast_Click() Data1.Recordset.MoveLast End Sub DAO Well use Data Access Object (DAO) methods to do what we did in the beginning of the last chapter: build a database and allow users to move through that database, editing it as they like. To construct a database, well create it, create a table with fields and add it to that database, and also construct an index for the database that will let us sort it. Working with DAO, you can use the Database and Recordset Data Access Objects in your procedures. The Database and Recordset objects each have properties and methods of their own, and you can write procedures that use these properties and methods to manipulate your data. To open a database in DAO, you just open a Database object or create a new one. This object can represent a Microsoft Jet database (.mdb) file, an ISAM database (for example, Paradox), or an ODBC database connected through the Microsoft Jet database engine. When the Database object is available, you create a Recordset object and use that objects methods, like MoveFirst and MoveNext, to work with the database.
Prepared By Fred Lisalitsa

47

@computer Studies Department

DAO also supports a client/server connection mode called ODBCDirect. ODBCDirect establishes a connection directly to an ODBC data source, without loading the Microsoft Jet database engine into memory, and is a good solution when you need ODBC features in your program. In the ODBCDirect object model, the Connection object contains information about a connection to an ODBC data source, such as the server name, the data source name, and so on. It is similar to a Database object; in fact, a Connection object and a Database object represent different references to the same object. (In this chapter, well stick with the Database/Recordset model.) DAO: Opening A Database To open an existing DAO database, you use the DAO OpenDatabase method, passing it the name of the database to open, and these arguments: Set database = workspace.OpenDatabase (name of database) DAO: Creating A Record Set After youve finished defining a database table with a DAO TableDef object, you can append that object to a Database object, which adds that table to that database. After youve installed the new table, you can use the OpenRecordset method to open a record set and start working with data: Set recordset = Database.OpenRecordset (source) Here are the argument for OpenRecordset: sourceA string specifying the source of the records for the new Recordset object. The source can be a table name, a query name, or an SQL statement that returns records. (For table-type Recordset objects in Jet-type databases, the source can only be a table name.) DAO: Adding A Record To A Record Set To add a new record to a DAO record set, you use the AddNew method (this method takes no parameters). After youve updated the fields of the current record, you save that record to the database with the Update method. Heres an example using AddNew. When the user clicks the Add button in our DAO code example, the daocode project (see the first topic in this chapter), we execute the AddNew method on the programs record set and clear the two data field text boxes: Private Sub Command1_Click() dbrecordset.AddNew Text1.Text = "" Text2.Text = "" End Sub Now users can enter data for the new records fields and click the programs Update button. When they click the Update Database button, the new data is written to the database. DAO: Editing A Record In A Record Set Besides adding new records to the record set, users might want to edit the existing records. To do that, you use the Edit method like this in our DAO code example, the daocode project (see the first topic in this chapter): Private Sub Command2_Click() dbrecordset.Edit End Sub After users edit the data in the records fields (by entering new data in the text fields in the daocode projects main window), they must update the database with the new data, and they do that in the daocode project by clicking the Update Database button. That button executes the Update method, as well see in the next topic. DAO: Updating A Record In A Record Set
Prepared By Fred Lisalitsa

48

@computer Studies Department

When the user changes the data in a record or adds a new record, we must update the database to record that change, and you use the record set Update method to do that: recordset.Update Private Sub Command3_Click() dbrecordset.field name = Text1.Text dbrecordset.field name = Text2.Text dbrecordset.Update End Sub DAO: Moving To The First Record In A Record Set To make the first record in a record set the current record, you use the MoveFirst method. For example, heres how we move to the first record when the user clicks the appropriate button in our DAO code example, the daocode project (see the first topic in this chapter): Private Sub Command4_Click() dbrecordset.MoveFirst ... End Sub After moving to the first record, we display that records fields in the two text boxes in the program, Text1 and Text2: Private Sub Command4_Click() dbrecordset.MoveFirst Text1.Text = dbrecordset.field name1 Text2.Text = dbrecordset.field name2 End Sub DAO: Moving To The Last Record In A Record Set To make the last record in a record set the current record, you use the MoveLast method. For example, heres how we move to the last record when the user clicks the appropriate button in our DAO code example, the daocode project (see the first topic in this chapter): Private Sub Command7_Click() dbrecordset.MoveLast ... End Sub After moving to the last record, we display that records fields in the two text boxes in the program, Text1 and Text2: Private Sub Command7_Click() dbrecordset.MoveLast Text1.Text = dbrecordset.field!name1 Text2.Text = dbrecordset.field!name2 End Sub DAO: Moving To The Next Record In A Record Set To move to the next record in a record set, making that record the current record, you use the MoveNext method. For example, in our DAO code example, the daocode project (see the first topic in this chapter), we move to the next record when the user clicks the appropriate button: Private Sub Command6_Click() dbrecordset.MoveNext ... We can check if weve gone past the end of the record set with the EOF property; if this property is True, we should move back one record: Private Sub Command6_Click() dbrecordset.MoveNext If dbrecordset.EOF Then Prepared By Fred Lisalitsa @computer Studies Department 49

dbrecordset.MovePrevious ... On the other hand, if the record weve moved to is a valid record, we display its fields in the programs two text boxes, Text1 and Text2: Private Sub Command6_Click() dbrecordset.MoveNext If dbrecordset.EOF Then dbrecordset.MovePrevious Else Text1.Text = dbrecordset.field!name1 Text2.Text = dbrecordset.field!name2

End If End Sub DAO: Moving To The Previous Record In A Record Set To move to the previous record in a record set, making that record the current record, you use the MovePrevious method. For example, in our DAO code example, the daocode project (see the first topic in this chapter), we move to the previous record when the user clicks the appropriate button: Private Sub Command5_Click() dbrecordset.MovePrevious ... We can check if weve gone past the beginning of the record set with the BOF property; if this property is True, we should move forward one record: Private Sub Command5_Click() dbrecordset.MovePrevious If dbrecordset.BOF Then dbrecordset.MoveNext ... On the other hand, if the record weve moved to is a valid record, we display its fields in the programs two text boxes, Text1 and Text2: Private Sub Command5_Click() dbrecordset.MovePrevious If dbrecordset.BOF Then dbrecordset.MoveNext Else Text1.Text = dbrecordset.field name1 Text2.Text = dbrecordset.field name2 End If End Sub DAO: Deleting A Record In A Record Set To delete a record in a DAO record set, you use the Delete method, and then you update the record set. For example, when the user clicks the Delete button in our DAO code example, the daocode project (see the first topic in this chapter), we clear the two text boxes, Text1 and Text2, that display the data for the current record and delete that record: Private Sub Command8_Click() Text1.Text = "" Text2.Text = "" dbrecordset.Delete End Sub DAO: Searching A Record Set Prepared By Fred Lisalitsa @computer Studies Department 50

You can search a record set with an index; we just set its Index property to the index we want to search and then set its Seek property to the string we want to search for. Lets see an example. When the user selects the Search menu item in our DAO code example, the daocode project (see the first topic in this chapter), we install the index based on the first field in the record set and show the dialog box named Search, which appears in Figure 25.3: Private Sub Search_Click() Set dbindex = td.Indexes(0) dbrecordset.Index = dbindex.Name SearchForm.Show End Sub After the user dismisses the Search dialog box, we retrieve the text to search for from that dialog boxs text box and place that text in the record sets Seek property, along with the command =, which indicates we want to find exact matches to the search text: Sub SearchTable() dbrecordset.Seek "=", SearchForm.Text1.Text ... Besides =, you can also search using <, <=, >=, and >. When the search is complete, we display the found record in the daocode projects main text boxes, Text1 and Text2: Sub SearchTable() dbrecordset.Seek "=", SearchForm.Text1.Text Text1.Text = dbrecordset.field!name1 Text2.Text = dbrecordset.field!name2 End Sub

Prepared By Fred Lisalitsa

51

@computer Studies Department

PROGRAMMING IN VISUAL BASIC SAMPLE PROGRAMS


TASK ONE Conversion 1. Open a project and add a new form by Click at the project menu Click at add form Click at open 2. Set properties for the form as Name Frmsamples Caption Conversions 3. Put a command on the form and set the properties as Name cmdbase Caption Change of bases 4. Double click at the Command then type the following code Private Sub CMDBASE_Click() Program to demonstrate change of bases Dim num1, num2, num3, num4, num5 As Long num1 = InputBox("Enter a decimal number", "Change of Bases", 0, 21, 4) num2 = Hex(num1) num3 = Oct(num1) MsgBox ("Your number in Hexadecimal is " & num2) MsgBox ("Your number in octal is " & num3) End Sub 5. Save and run the program TASK TWO Use of date 1. Open a project and add a new form 2. Set properties for the form as Name Frmsamples Caption Conversions 3. Put a command on the form and set the properties as Name cmddate Caption Working with dates 4. Add Four labels and four Textboxes on the form and set there properties as For label For Textbox Name Caption Name Lblday Day Txtday Lblyear Year Txtyear Lblmonth Month Txtmonth Lblweek Weekday Txtweek

5.

Double click at the Command then type the following code Private Sub CMDDATE_Click() 'Program to demonstrate the the use of date Dim dates As Date Dim d, m, y, w As Long dates = InputBox("Enter any date of he year", "Use of Dates", "1/1/04", 23, 30) 52
@computer Studies Department

Prepared By Fred Lisalitsa

d = Day(dates) m = Month(dates) y = Year(dates) w = Weekday(dates) txtday = d txtmonth = m txtyear = y txtweek = w End Sub 6. Save and run the program TASK THREE Use of string data type 1. Open a project and add a new form 2. Set properties for the form as Name Frmsamples Caption Handling of strings 3. Put a command on the form and set the properties as Name cmdstring Caption strings 4. Add 3 labels and 3 Textboxes on the form and set there properties as For label For Textbox Name Caption Name Lbllower Lower TxtLower Lblupper Upper TxtUpper Lbllength Length TxtLength 5. Double click at the Command then type the following code Private Sub CMDSTRING_Click() 'Program to demonstrate the use of strings Dim fstring As String Dim message, title As String Dim t As Integer fstring = InputBox("Enter any word of your choice", "Use of Strings", "Coming Home", 34, 67) message = "The length of the string is " & Len(fstring) & " Characters" title = " The number of characters" t = 4096 + 48 MsgBox message, t, title txtlower = LCase(fstring) txtupper = UCase(fstring) txtlenght = Len(fstring) End Sub 6. Save and run the program TASK FOUR Use of arithmetic operrators 1. Open a project and add a new form 2. Set properties for the form as Name Frmoperators Caption Arithmetic Operators 3. Add 3 labels and 3 Textboxes on the form and set there properties as For label For Textbox Name Caption Name Prepared By Fred Lisalitsa @computer Studies Department 53

Lblfirst Lblsecond Lblans 4.

The first number Txtfirst The Second number Txtsecond Your answer is Txtans

Add 4 commands on the form and set there properties as follows Name Caption Cmdadd Add Cmdsub Subtract Cmddivide Divide Cmdmultiply Multiply Double click at each Command then type the following code Add Private Sub cmdadd_Click() txtans = Val(txtfirst) + Val(txtsecond) End Sub Divide Private Sub cmddivide_Click() txtans = Val(txtfirst) / Val(txtsecond) End Sub Multiply Private Sub cmdmultiply_Click() txtans = Val(txtfirst) * Val(txtsecond) End Sub

5.

Subtract Private Sub cmdsub_Click() txtans = Val(txtfirst) - Val(txtsecond) End Sub 6. Save and run the program

TASK FIVE Use of Logical operators and if A Use of Logical and Comparison operators 1 Add a command on the any form and set its properties to Name Cmdif Caption Compare Three numbers 2 Double click the command and type the following code Private Sub CMDif_Click() 'Program to compare Three Numbers Use of If, Comparison ans logical operators Dim a, b, c As Integer Dim message, title As String Dim t As Integer a = InputBox("Enter the first number", "The First number", 0, 45, 70) b = InputBox("Enter the second number", "The Second number", 0, 45, 70) c = InputBox("Enter the Third number", "The Third number", 0, 45, 70) If a > b And a > c Then message = "The greater number is " & a Prepared By Fred Lisalitsa @computer Studies Department 54

title = " The bigger number" t = 4096 + 16 + 64 MsgBox message, t, title ElseIf b > a And b > c Then message = "The greater number is " & b title = " The bigger number" t = 4096 + 48 MsgBox message, t, title ElseIf c > a And c > b Then MsgBox "The bigger Number is " & c Else MsgBox ("Two or all the numbers are equal") End If End Sub 6 Save and Run the program B Use of Xor 1 Add a command on the any form and set its properties to Name Cmdxor Caption XOR 2 Double click the command and type the following code Private Sub cmdxor_Click() Program to demonstrate the use of xor Dim Y, X, Z As Integer Dim message, title As String Dim t As Integer Y = InputBox("Enter the first number", "The First number", 0, 45, 70) X = InputBox("Enter the second number", "The Second number", 0, 45, 70) Z = InputBox("Enter the third number", "The Third number", 0, 45, 70) If Y > X Xor Y > Z Then message = " " & Y & " is greater " & X & " But Less than " & Z title = " Use of xor" t = 4096 + 64 MsgBox message, t, title End If End Sub C Use of msgbox and if 1 Add a command on the any form and set its properties to Name CmdMsgBoxandIf Caption Use of Msgbox and If 2 Double click the command and type the following code Private Sub cmdmsgboxif_Click() 'Program to give the use chance of adding or subtracting Dim num1, num2, ans As Single num1 = InputBox("Enter the first number", "The First number", 0, 60, 34) num2 = InputBox("Enter the second number", "The Second number", 0, 45, 70) If MsgBox("Do you want to Add the two number ?", vbYesNo, "Use of MsgBox and If")_ = vbYes Then ans = Val(num1) + Val(num2) MsgBox "The Numbers were added the sum is " & ans Else ans = num1 - num2 Prepared By Fred Lisalitsa @computer Studies Department 55

MsgBox "The Numbers were Subtracted The Answer is " & ans End If End Sub TASK SIX Use of Select Case A 1 Add a command on the any form and set its properties to Name Cmdselect1 Caption Use of select Case 1 2 Double click the command and type the following code Private Sub Cmdselect1_Click() 'Program to Determine the grade of the student marks Dim Marks As Long Marks = InputBox("Enter the marks for the student", "Marks for the student", 0, 34, 70) Select Case Marks Case 0 To 39 MsgBox ("The Grade is Fail") Case 40 To 59 MsgBox ("The Grade is Pass") Case 60 To 79 MsgBox ("The Grade is Credit") Case 80 To 100 MsgBox ("The Grade is Dist") Case Else MsgBox ("The marks are out of range") End Select End Sub B 1

2.

Add a command on the any form and set its properties to Name Cmdselect2 Caption Use of select Case 2 Add a textbox name it txtcolour and a label: name Lblcolour and Caption The colour and arrange them appropriately

Double click the command and type the following code Private Sub Cmdselect2_Click() 'Program to demonstrate the use of Select ansd Colour Dim colname As String colname = InputBox("Enter the name of the colour you need", "Enter the Colour Name") colname = Trim(UCase(colname)) 'Trimming excess spaces and changing to upper case Select Case colname Case Is = "BLUE" txtcolour.BackColor = vbBlue Case Is = "GREEN" txtcolour.BackColor = vbGreen Case Is = "YELLOW" txtcolour.BackColor = vbBYELLOW Case Is = "BLACK" Prepared By Fred Lisalitsa @computer Studies Department 56

txtcolour.BackColor = vbBlack Case Is = "RED" txtcolour.BackColor = vbRed Case Else txtcolour.BackColor = vbWhite txtcolour.Text = "UNKNOWN COLOUR" End Select End Sub

C Use of Select and MsgBox 1 Add a command on the any form and set its properties to Name Cmdselect3 Caption Use of select and Msgbox 2 Double click the command and type the following code Private Sub cmdselect3_Click() 'Program to demonstrate the use of msgBox and the value Dim t, reply As Integer Dim number1, number2, ans As Integer stop1: number1 = InputBox("Enter the first number", "The First number", 0, 60, 34) number2 = InputBox("Enter the second number", "The Second number", 0, 45, 70) If number1 < 1000 Or number2 < 1000 Then t = 32 + 2 reply = MsgBox("You have not entered the correct numbers They should be a bove_ 1000", t, "quit") Select Case reply Case Is = 3 MsgBox " you have chosen Abort" End Case Is = 5 MsgBox " you have chosen Ignore" ans = number1 * number2 MsgBox " your answer is " & ans Case Is = 4 MsgBox " you have chosen Retry" GoTo stop1 End Select End If End Sub

TASK SEVEN Use of Repetition Control Structures A For. Next (i) 1 Add a command on the any form and set its properties to Name CmdFornext Caption For Next 1 2 Double click the command and type the following code Private Sub cmdfornext_Click() 'Program to add ten numbers Dim num, sum As Long Prepared By Fred Lisalitsa @computer Studies Department 57

Dim i As Integer sum = 0 For i = 1 To 10 num = InputBox("Enter a number") sum = sum + num Next i MsgBox "The sum is " & sum End Sub A For. Next (II) 1 Add a command on the any form and set its properties to Name CmdFornext2 Caption For Next 2 2 Double click the command and type the following code Private Sub cmdfornext2_Click() 'Program to Output Odd integers on the form Dim i As Integer For i = 1 To 20 Step 2 Print i Next i End Sub

B Do While 1 Add a command on the any form and set its properties to Name Cmddowhile Caption Do While 2 Double click the command and type the following code Private Sub cmddowhile_Click() 'Program to Determine the grade of the student marks Dim Marks, d, f, p, o, c As Long Marks = 0 Do While Marks <> -1 Marks = InputBox("Enter the marks for the student Enter -1 to stop", "Marks for the student", 0, 34, 70) Select Case Marks Case 0 To 39 f=f+1 Case 40 To 59 p=p+1 Case 60 To 79 c=c+1 Case 80 To 100 d=d+1 Case Else o=o+1 End Select Loop MsgBox ("The Fails are " & f) MsgBox ("The Passs are " & p) MsgBox ("The Credits are " & c) MsgBox ("The Dist are" & d) MsgBox ("The out of range are " & o) Prepared By Fred Lisalitsa @computer Studies Department 58

End Sub

C Do Until 1 Add a command on the any form and set its properties to Name Cmddountil Caption Do Until 2 Double click the command and type the following code Private Sub cmddountil_Click() 'Program to add ten numbers using Do until loop Dim num, sum As Long Dim i As Integer Dim t As Boolean sum = 0 t = False Do num = InputBox("Enter a number") sum = sum + num If MsgBox("Do you want to stop", vbYesNo, "Continue") = vbYes Then t = True End If Loop Until t MsgBox "The sum is " & sum End Sub D While Wend 1 Add a command on the any form and set its properties to Name CmdWhileWend Caption While Wend 2 Double click the command and type the following code Private Sub cmdwhilewend_Click() 'program to determine the largest from Ten numbers Dim number, big As Double Dim k As Integer k=1 number = InputBox("Enter the first number", "The First Number", 0, 45, 78) big = number While k < 10 k=k+1 number = InputBox("Enter the Next number", "The Next Number", 0, 45, 78) If number > big Then big = number End If Wend MsgBox ("The bigger number is " & big) End Sub

TASK EIGHT Use of Arrays and User defined data type A Arrays (ONE Dimensional) 1. Open a project and add a new form by Click at the project menu Click at add form Prepared By Fred Lisalitsa 59

@computer Studies Department

2.

3.

Click at open Set properties for the form as Name Frmsamples Caption Arrays and User defined Add a command on the form and set the properties as Name cmdarray1 Caption One Dimensional array 1 Double click the command and type the following code Private Sub cmdarray1_Click() 'Program to Input ten values in an array Dim num(10) As Long 'Input of the Ten numbers For i = 1 To 10 num(i) = InputBox("Enter a number") Next i 'Output of the ten numbers on the form For i = 1 To 10 Print num(i) Next i

4.

End Sub B Arrays Use of Redim Statement 1. Add a command on the form and set the properties as Name cmdarray2 Caption One Dimensional array 2 2. Double click the command and type the following code Private Sub cmdarray2_Click() 'Program to demonstrate the use of redim Statemnet Dim num() As Long Dim k, i As Integer k = InputBox("How many Values Do you want to enter", "Numbers", 10) ReDim num(k) 'Input of the numbers For i = 1 To k num(i) = InputBox("Enter a number") Next i 'Output of the ten numbers on the form For i = 1 To k Print num(i) Next i End Sub C Arrays Two Dimensional array 1. Add a command on the form and set the properties as Name cmdarray3 Caption Two Dimensional array 2. Double click the command and type the following code Private Sub cmdarray3_Click() Prepared By Fred Lisalitsa

60

@computer Studies Department

'Program to Input values in a two dimensional array Dim num(4, 4) As Long Dim i, j As Integer 'Input of the numbers For i = 1 To 4 For j = 1 To 4 num(i, j) = InputBox("Enter a number") Next j Next i 'Output of the ten numbers on the form For i = 1 To 4 Print "The " & i; "Row" For j = 1 To 4 Print num(i, j) Next j Next i End Sub D User defined type data 1. Add a command on the form and set the properties as Name cmduser1 Caption User Defined 2. Double click the command and type the following code Private Sub cmduser1_Click() 'Program todemonstrate input of one record and output using User defined Dim studrec As student 'This is for input studrec.name = InputBox("Enter Your name") studrec.admno = InputBox("Enter The admission Number of the student") studrec.fees = InputBox("Enter The fees paid by the student") 'This is for output MsgBox ("Your Name is " & studrec.name) MsgBox ("Your admission number is " & studrec.admno) MsgBox ("Your fees is " & studrec.fees) End Sub E User defined type data The use of With Structure 1. Add a command on the form and set the properties as Name cmduser2 Caption User Defined & With structure 2. Double click the command and type the following code Private Sub cmduser2_Click() 'Program to demonstrate input of one record and output using User defined and With Structure Dim studrec As student 'This is for input With studrec .name = InputBox("Enter Your name") .admno = InputBox("Enter The admission Number of the student") .fees = InputBox("Enter The fees paid by the student") End With 'This is for output Prepared By Fred Lisalitsa @computer Studies Department 61

MsgBox ("Your Name is " & studrec.name) MsgBox ("Your admission number is " & studrec.admno) MsgBox ("Your fees is " & studrec.fees) End Sub F User defined type data The use of Array 1. Add a command on the form and set the properties as Name cmduser3 Caption User Defined & Array 2. Double click the command and type the following code Private Sub Cmduser3_Click() 'Program to demonstrate input of one record and output using User defined and With Structure Dim studrc(10) As student 'This is for input For i = 1 To 4 With studrc(i) .name = InputBox("Enter Your name") .admno = InputBox("Enter The admission Number of the student") .fees = InputBox("Enter The fees paid by the student") End With Next i 'This is for output For i = 1 To 4 With studrc(i) Print .name & " " & .admno & " " & .fees End With Next i End Sub

TASK NINE Sup Programming in Visual Basic A Use of procedure without Parameters 1. Add a command on the form and set the properties as Name cmdsub1 Caption Subroutine 2. Type the following module in the General declaration area Sub Traingle() 'Subroutine Const t = 0.5 area = t * h * b End Sub 3. Double click the command and type the following code Private Sub cmdsub1_Click() 'Program used to calculate the area of a triangle using subroutines 'Note All the variables have been declared at form level general Declaration area h = InputBox("Enter the height of the Triangle") b = InputBox("Enter the base of the Triangle") Call Traingle 'Calling a subroutine called adding MsgBox ("Your answer is " & area) 'Note that area as a variable is declared at form level ie General area End Sub Prepared By Fred Lisalitsa @computer Studies Department 62

B Use of procedure with Parameters 1. Add a command on the form and set the properties as Name cmdsub2 Caption Subroutine With Parameters (ByVal) 2. Type the following module in the General declaration area Sub Multiply(ByVal mult As Double, ByRef m1, m2 As Long) mult = m1 * m2 MsgBox ("Your answer is " & mult) 'Can only be output in the procedure End Sub 3. Double click the command and type the following code Private Sub Cmdsub2_Click() 'program to Multiply two numbers using parameters Dim ans As Double Dim No1, no2 As Long No1 = InputBox("Enter the first Number") no2 = InputBox("Enter the Second Number") Call Multiply(ans, No1, no2) End Sub C Use of procedure with Parameters both ByVal and ByRef 1. Add a command on the form and set the properties as Name cmdsub3 Caption Subroutine with Parameters ByVal & ByRef 2. Type the following module in the General declaration area Sub Multiply1(ByVal p1, p2 As Single, m2 As Double) 'Note p1 and p2 are Value Parameters and M2 is Reference Parameter m2 = p1 * p2 End Sub 3. Double click the command and type the following code Private Sub cmdsub3_Click() 'program to Multiply two numbers using parameters Dim Number1, Number2 As Single Dim m1 As Double Number1 = InputBox("Enter the first Number") Number2 = InputBox("Enter the Second Number") Call Multiply1(Number1, Number2, m1) MsgBox ("Your answer is " & m1) End Sub D Use of Function without Parameters 1. Add a command on the form and set the properties as Name cmdfunct1 Caption Function 2. Type the following Function in the General declaration area Function add() As Integer add = a * b End Function 3. Double click the command and type the following code Private Sub Cmdfunct1_Click() 'Program Using Function to add two numbers Prepared By Fred Lisalitsa @computer Studies Department 63

'Note a and b Must be declared in the general Declaration section a = InputBox("Enter the first number") b = InputBox("Enter The second nunmber") MsgBox ("your answer is " & add) End Sub E Use of Function with Parameters 1. Add a command on the form and set the properties as Name cmdfunct2 Caption Function with Parameters 2. Type the following module in the General declaration area Function Aver(ByVal S1, S2, S3 As Long) As Double Dim k, tot As Double 'This are local Variables tot = Val(S1) + Val(S2) + S3 k = tot / 3 Aver = k End Function 3. Double click the command and type the following code Private Sub Cmdfunct2_Click() 'Program Using Function to get average of three numbers using parameters Dim Nu1, Nu2, Nu3 As Long Nu1 = InputBox("Enter the first number") Nu2 = InputBox("Enter the second nunmber") Nu3 = InputBox("Enter the third nunmber") MsgBox ("your ans is " & Aver(Nu1, Nu2, Nu3)) End Sub

Prepared By Fred Lisalitsa

64

@computer Studies Department

KABETE TECHNICAL TRAINING INSTITUTE COMPUTER STUDIES DEPARTMENT VBPROGRAMMING


CLASS ASSIGNMENT Question one Create the following table Registration Field name 1) Name 2) IDNO 3) Gender 4) Dept 5) Course 6) Dtadmit 7) Diatrict 8) Admno Description Name of the student Identification number for the student The gender of the student I.e. Male or Female Department of the student Course of the student Date admitted District of birth Admission number of the student

Fees payment Field name 1) Admno 2) Feespaid 3) Feestopay 4) Balance 5) Name 6) Prepaid 7) Course 8) Dept Description Admission number Fees paid by the student Total amount for the term Balance for the student Name of the student Any Pre payment made by the student Course for the student Department for the student

Boarding Field name 1) Admno 2) Dept 3) Dorm 4) Cube 5) Bedno 6) Course Description Admission number for the student Department for the student Dormitory allocated to the student Cube number allocated to the student Bed number for the student Course taken by the student

Library Field name 1) Libno 2) Admno 3) Bktitle 4) Bkedit 5) Name 6) Dtborrow 7) Dtreturn Description Library number Admission number Book Title Book Edition Name of the student Date the book was borrowed Date the book will be returned

Question two Create a form for each of the tables above and add the following commands Name Caption 1) Cmdadd Add A new Record 2) Cmdupdate Update 3) Cmdedit Edit a record 4) Cmdnext Move next 5) Cmdprevious Move Previous 6) Cmdfirst Move First

Prepared By Fred Lisalitsa

65

@computer Studies Department

7) 8) 9) 10)

Cmdlast Cmdsearch Cmddelete Cmdexut

Move Last Search for a record Delete a record Exit

NB As you prepare the forms give the name of the text box to correspond with the name of the field E.g Name of the field Name of the text box Admno Txtadmno Libno Txtlibn e.t.c.

This is for registration form alone Add data1 object Name DTKABETE CAPTION

College Administration System

Question Three Add the following programs to Registration Form

PROGRAMS
CMDADD COMMAND Private Sub CMDADD_Click() If MsgBox("ADD NEW RECORD?", vbYesNo) = vbYes Then DTKABETE.Recordset.AddNew Else MsgBox ("RECORD NOT ADDED") End If End Sub

CMDLAST COMMAND Private Sub CMDLAST_Click() If MsgBox("Move the the last record ?", vbYesNo) = vbYes Then DTKABETE.Recordset.MoveLast End If End Sub

CMDDELETE COMMAND Private Sub CMDDELETE_Click() If MsgBox("REALLY DELETE?", vbYesNo) = vbYes Then DTKABETE.Recordset.Delete Else MsgBox ("RECORD NOT DELETED") End If End Sub

CMDNEXT COMMAND Private Sub CMDNEXT_Click() If DTKABETE.Recordset.EOF Then MsgBox ("This is the last record") Else DTKABETE.Recordset.MoveNext End If End Sub

CMDUPDATE COMMAND Private Sub CMDupdate_Click() If MsgBox("SAVE THE RECORD?", vbYesNo) = vbYes Then DTKABETE.Recordset.Update Else MsgBox ("RECORD NOT SAVED") End If End Sub

CMDEXIT COMMAND Private Sub CMDEXIT_Click() If MsgBox("DO YOU WANT TO EXIT?", vbYesNo) = vbYes Then Unload Me End If End Sub

CMDFIRST COMMAND Private Sub CMDFIRST_Click() If MsgBox("Move the the first record ?", vbYesNo) = vbYes Then DTKABETE.Recordset.MoveFirst End If End Sub
QUESTION Five On fees payment form add the following codes In general declaration area type the following Dim dbkabete as database Dim recfees as recordset In the form load type the following TXTFeespaid= TXTFeestopay=

CMDPREVIOUS COMMAND Private Sub cmdprevious_click() If DTKABETE.Recordset.BOF Then MsgBox ("This is the First record") Else DTKABETE.Recordset.MovePrevious Endif End Sub
Set dbkabete=opendatabase(c:\kabete\kabete.mdb) Set recfees=dbkabete.openrecosrdset(feespayeme nt) Recfees.index = inadmno Prepare three modules as follows Sub clear() TXTAdmno = TXTBalance = TXTName =

Prepared By Fred Lisalitsa

66

@computer Studies Department

TXTPrepaid = TXTCourse = TXTDept = END SUB

CMDLAST COMMAND Private Sub CMDLAST_Click() If MsgBox("Move the the last record ?", vbYesNo) = vbYes Then Recfees.MoveLast Call callrecord End If End Sub

SUB ADD() RECFEES!ADMNO=TXTAdmno RECFEES!FEESPAID =TXTFeespaid RECFEES!FEESTOPAY= TXTFeestopay RECFEES!BALANCE=TXTBalance RECFEES!NAME = TXTName RECFEES!PREPAID=TXTPrepaid RECFEES!COURSE=TXTCourse RECFEES!DEPT=TXTDept END SUB SUB callrecord() TXTAdmno =RECFEES!ADMNO TXTFeespaid = RECFEES!FEESPAID TXTFeestopay =RECFEES!FEESTOPAY TXTBalance =RECFEES!BALANCE TXTName =RECFEES!NAME TXTPrepaid= RECFEES!PREPAID TXTCourse =RECFEES!COURSE TXTDept = RECFEES!DEPT END SUB ADD THE FOLLOWING PROGRAMS CMDADD COMMAND Private Sub CMDADD_Click() If MsgBox("ADD NEW RECORD?", vbYesNo) = vbYes Then Call clear Recfees.AddNew Else MsgBox ("RECORD NOT ADDED") End If End Sub

CMDNEXT COMMAND Private Sub CMDNEXT_Click() If Recfees.EOF Then MsgBox ("This is the last record") Else Recfees.MoveNext Call callrecord End If End Sub

CMDUPDATE COMMAND Private Sub CMDupdate_Click() If MsgBox("SAVE THE RECORD?", vbYesNo) = vbYes Then Call add Recfees.Update Else MsgBox ("RECORD NOT SAVED") End If End Sub

CMDPREVIOUS COMMAND Private Sub cmdprevious_click() If Recfees.BOF Then MsgBox ("This is the First record") Else Recfees.MovePrevious Call callrecord Endif End Sub CMDSERACH COMMAND Private sub CMDsearch_click() Dim inadmno as double Inadmno=inputbox(Enter the admission number to search) Recfees.seek=,inadmno If recfees.nomartch then Msgbox(Record not Found) Else Call callrecord End if END SUB CMDEDIT COMMAND Private sub CMDEDIT_click() Dim inadmno as double Inadmno=inputbox(Enter the admission number to EDIT) Recfees.seek=,inadmno If recfees.nomartch then Msgbox(Record not Found) Else If msgbox(modify this record ?,vbyesno)=vbyes then Call callrecord Recfees.edit endif End if End Sub

CMDDELETE COMMAND Private sub CMDDELETE_click() Dim inadmno as double Inadmno=inputbox(Enter the admission number to EDIT) Recfees.seek=,inadmno If recfees.nomartch then Msgbox(Record not Found) Else If msgbox(Delete this record ?,vbyesno)=vbyes then Recfees.delete Call clear Recfees.movenext endif End if END SUB CMDEXIT COMMAND Private Sub CMDEXIT_Click() If MsgBox("DO YOU WANT TO EXIT?", vbYesNo) = vbYes Then Unload Me End If End Sub

CMDFIRST COMMAND Private Sub CMDFIRST_Click() If MsgBox("Move the the first record ?", vbYesNo) = vbYes Then Recfees.MoveFirst Call callrecord End If End Sub

Prepared By Fred Lisalitsa

67

@computer Studies Department

KABETE TECHNICAL TRAINING INSTITUTE


End Sub

QUESTION SIX
Prepare library form ie Add textboxes, labels and the commands 1) Add an ADO Object by 2) Right click at the toolbox 3) Choose components 4) Look for Microsoft ADO Data Control 6.0 5) Click at checkbox on the left then apply 6) You will see a new object on the toolbox add it to the form Right click at the ADO OBJECT and select properties Select use connection string option and click Build Select Microsoft jet 4.0 ole db provider for Access 2000 and click next Click the button and select database name I.E. Kabete by browsing Click Test Connection in the Data link Properties Window Until connection succeeded and click OK Click Apply then O.K

MOVE LAST COMMAND


Private Sub CMDLAST_Click() If MsgBox("Move the the last record ?", vbYesNo) = vbYes Then ADOKABETE.Recordset.MoveLast End If End Sub

MOVE NEXT COMMAND


Private Sub CMDNEXT_Click() If ADOKABETE.Recordset.EOF Then MsgBox ("This is the last record") Else ADOKABETE.Recordset.MoveNext End If End Sub

Add the following codes

ADD COMMAND
Private Sub CMDADD_Click() If MsgBox("ADD NEW RECORD?", vbYesNo) = vbYes Then ADOKABETE.Recordset.AddNew Else MsgBox ("RECORD NOT ADDED") End If End Sub

UPDATE COMMAND
Private Sub CMDUPDATE_Click() If MsgBox("SAVE THE RECORD?", vbYesNo) = vbYes Then ADOKABETE.Recordset.Update Else MsgBox ("RECORD NOT SAVED") End If End Sub

DELETE COMMAND
Private Sub CMDDELETE_Click() If MsgBox("REALLY DELETE?", vbYesNo) = vbYes Then ADOKABETE.Recordset.Delete Else MsgBox ("RECORD NOT DELETED") End If End Sub

MOVE PREVIOUS COMMAND


Private Sub cmdprevious_click() If ADOKABETE.Recordset.BOF Then MsgBox ("This is the First record") Else ADOKABETE.Recordset.MovePrevious End Sub End If

EDIT COMMAND
Private Sub CMDEDIT_Click() If MsgBox("EDIT THIS RECORD?", vbYesNo) = vbYes Then ADOKABETE.Recordset.EditMode Else MsgBox ("RECORD NOT ADDED") End If End Sub

SEARCH COMMAND
Private Sub CMDSEARCH_Click() Dim inadmno As integer Dim VARBOOKMARK As Variant With ADOKABETE.Recordset VARBOOKMARK = .Bookmark .Find "COURSECODE='indmno'", 0, adSearchForward, adBookmarkCurrent If .EOF Or .BOF Then .Bookmark = VARBOOKMARK MsgBox ("RECORD NOT FOUND") End If End With End Sub

EXIT COMMAND
Private Sub CMDEXIT_Click() If MsgBox("DO YOU WANT TO EXIT?", vbYesNo) = vbYes Then Unload Me End If End Sub

MOVEFAST COMMAND
Private Sub CMDFIRST_Click() If MsgBox("Move the the first record ?", vbYesNo) = vbYes Then ADOKABETE.Recordset.MoveFirst End If

Prepared By Fred Lisalitsa

68

@computer Studies Department

KABETE TECHNICAL TRAINING INSTITUTE

FILE ORGANIZATION
CREATING A FILE SEQUENTIAL FILES Private Sub Command1_Click() Dim i As Integer Dim name As String On Error GoTo FileError Open "c:\file.txt" For Output As #1 For i = 1 To 10 name = InputBox("Enter the name") Print #1, name Next i Close #1 Exit Sub FileError: MsgBox "File Error!" End Sub

DETERMINING THE LENGTH OF A FILE


Private Sub Command2_Click() 'getting the length of a file MsgBox "The file.txt file is" & Str(FileLen("c:\file.txt")) & _ " bytes long." End Sub

OUTPUT OF A FILE
Private Sub Command4_Click() Dim int1 As String Dim i As Integer Open "c:\file.txt" For Input As #1 i=0 Do Until EOF(1) Input #1, int1 txtout(i).Text = int1 i=i+1 Call add Loop Close #1 End Sub
Prepared By Fred Lisalitsa 69 @computer Studies Department

KABETE TECHNICAL TRAINING INSTITUTE

CREATING OF A CONTROL ARRAY


Sub add() Dim k As Integer k = txtout().Count Load txtout(k) txtout(k).Top = txtout(k - 1).Top + 400 txtout(k).Visible = True End Sub

APPENDING A FILE
Private Sub Command5_Click() Dim i As Integer Dim name As String On Error GoTo FileError Open "c:\file.txt" For Append As #1 For i = 1 To 10 name = InputBox("Enter the name") Print #1, name Next i Close #1 Exit Sub FileError: MsgBox Err.Description End Sub

SEARCHING A FILE
Private Sub Command6_Click() Dim int1, inname As String Dim i As Integer Open "c:\file.txt" For Input As #1 i=0 inname = InputBox("enter the name to search") Do Until EOF(1) Input #1, int1 If inname = int1 Then MsgBox "name found" Exit Do End If If EOF(1) Then MsgBox "file not found" End If Loop Close #1 Prepared By Fred Lisalitsa

70

@computer Studies Department

KABETE TECHNICAL TRAINING INSTITUTE

End Sub

RANDOM FILES
Private Sub form_load() Call WRITING Call READING Unload Me End Sub Private Sub READING() Dim name As String, numb As Integer Open "c:\trial.txt" For Random As #1 Do Until EOF(1) numb = InputBox("enter the number to be of record to be read", , 1) Get #1, numb, name MsgBox "the read name is " & name Loop Close #1 End Sub Private Sub WRITING() Dim Y As String Open "c:\trial.txt" For Random As #1 For num = 1 To 5 Y = InputBox("Enter the name to be writen into the file", , 0) Put #1, num, Y Next num Close #1 End Sub

Prepared By Fred Lisalitsa

71

@computer Studies Department

You might also like