48
1. Objects Characteristics -building blocks of Visual Basic - Object types already created - we make new instances - Object types ' borrowed' from Windows environment - Individual entities that are somewhat self-contained - Can interact with other objects - Some behavior 'built-in' 2. An object has:

vb 6.0 notes

Embed Size (px)

DESCRIPTION

visual basic notes

Citation preview

1. Objects

Characteristics -building blocks of Visual Basic - Object types already created - we make new instances - Object types ' borrowed' from Windows environment - Individual entities that are somewhat self-contained - Can interact with other objects - Some behavior 'built-in'

2. An object has:

Properties - individual characteristics of the object Events - stimuli from the user, environment, or other objects that the object can respond to Methods - specialized commands that the object can do - allows you to manipulate

3. Selected Controls

Form - abbreviation: frm - main property: varies - main event: load (activated whenever the form shows up on screen) - main uses; serves as a container for all other controls - background for the program - load event used to contain code for early in the program run

4. Sample Code:

Private Sub Form_Click()'when clicked show in the label that this 'is a formlblLabel.Caption = "This is the Form"End Sub

5. Picture box

Main property: Picture Main event: click Abbreviation: pic Main uses: display graphic image on screen

6. Sample Code:

Private Sub picIUPUI_Click()'when clicked show in the label this is a'picture boxlblLabel.Caption = "This is a Picture Box"End Sub

7. Label

Main property: caption Main event: click Abbreviation: lbl Main uses: primary form of text OUTPUT in VB, display text on screen show text that the user cannot directly change, works like print command in other languages

8. Text box

Main property: text Main event: change Abbreviation: txt Main uses: primary form of text INPUT in VB, displays CHANGEABLE text on screen, often works like INPUT command in other languages

9. Command Button

Main property: caption Main event: click Abbreviation: cmd Main uses: indicated user's desire to do something, frequently houses significant amount of program code, graphically shows being depressed, easily recognized as something to click

10. Sample Code:

Private Sub cmdQuit_Click()'when the user clicks here end the programEndEnd Sub

11. Scroll bar

Main property: value Main event: change Abbreviation: hsc (horizontal), vsc (vertical) Main uses: primary form of INTEGER input in VB, allows user to input numeric value graphically, range can be determined at design time, allows little opportunity for error

12. Sample Code:

Private Sub hscHorizontal_Change()'when the user moves the scrollbar indicate in the'label that this is a horizontal scroll barlblLabel.Caption = "This is a horizontal scroll bar " & hscHorizontal.ValueEnd Sub

13. Option button

Main property: value (true or false) Main event: click Abbreviation: opt Main uses: allows user to check ONLY ONE of a series of options, grouped in a form or frame, when one is true all others are false, like a car radio

14. Check box

Main property: value (checked, unchecked or grayed) Main event: click Abbreviation: chk Main uses: allows user to check one OR MORE of a series of options, can also be grouped, more than one can be checked at a time

outlineObjects Characteristics -building blocks of Visual Basic - Object types already created - we make new instances - Object types ' borrowed' from Windows environment - Individual entities that are somewhat self-contained - Can interact with other objects - Some behavior 'built-in' An object has: Properties - individual characteristics of the object Events - stimuli from the user, environment, or other objects that the object can respond to Methods - specialized commands that the object can do - allows you to manipulate Selected Controls Form - abbreviation: frm - main property: varies - main event: load (activated whenever the form shows up on screen) - main uses; serves as a container for all other controls - background for the program - load event used to contain code for early in the program run Sample Code: Private Sub Form_Click()'when clicked show in the label that this 'is a formlblLabel.Caption = "This is the Form"End Sub Picture box Main property: Picture Main event: click Abbreviation: pic Main uses: display graphic image on screen Sample Code: Private Sub picIUPUI_Click()'when clicked show in the label this is a'picture boxlblLabel.Caption = "This is a Picture Box"End Sub Label Main property: caption Main event: click Abbreviation: lbl Main uses: primary form of text OUTPUT in VB, display text on screen show text that the user cannot directly change, works like print command in other languages Text box Main property: text Main event: change Abbreviation: txt Main uses: primary form of text INPUT in VB, displays CHANGEABLE text on screen, often works like INPUT command in other languages Command Button Main property: caption Main event: click Abbreviation: cmd Main uses: indicated user's desire to do something, frequently houses significant amount of program code, graphically shows being depressed, easily recognized as something to click Sample Code: Private Sub cmdQuit_Click()'when the user clicks here end the programEndEnd Sub Scroll bar Main property: value Main event: change Abbreviation: hsc (horizontal), vsc (vertical) Main uses: primary form of INTEGER input in VB, allows user to input numeric value graphically, range can be determined at design time, allows little opportunity for error Sample Code: Private Sub hscHorizontal_Change()'when the user moves the scrollbar indicate in the'label that this is a horizontal scroll barlblLabel.Caption = "This is a horizontal scroll bar " & hscHorizontal.ValueEnd Sub Option button Main property: value (true or false) Main event: click Abbreviation: opt Main uses: allows user to check ONLY ONE of a series of options, grouped in a form or frame, when one is true all others are false, like a car radio Check box Main property: value (checked, unchecked or grayed) Main event: click Abbreviation: chk Main uses: allows user to check one OR MORE of a series of options, can also be grouped, more than one can be checked at a time outlineProperties Properties are a number of variables associated with an object Each object has a different list of properties Some properties are common to most objects (visible) Some properties are specific to only one type of object (Max, Min in scroll bars) Properties Characteristics Can have different types of values: - Text (caption)- Numeric (min, max)- Boolean - True/False (visible) Properties are used to: Refine an object's appearance (BackColor) Refine an object's behavior (Enabled) Set up the object so it will do what the programmer wants (Design time) Change the characteristics of the property while the program is running (Run time) Properties can be changed at: Design time: - as the program is being built- uses the properties box - All properties will be set this way when the program starts execution Properties can be changed at: Run time: - while the program is running - is accomplished using code - allows properties to be changed on the fly - allows response to environmental (user) input Example: MyFirst used - design time to set up the BackColor of the picture boxes - run time to set up the BackColor of the form Methods A special kind of command attached to specific objects Works only with the object it is attached to Some objects (check boxes) have a few methods Others (data controls) have many Method Characteristics Usually found searching the online help Activated only in run time Relatively limited use Syntax: Object.Method Examples Move event - used to move an object Syntax - Object.Move X, Y, Height, Width - where X and Y are coordinates the object will be moved to - height and width are the size of the object Common Methods Hide, Show used with forms AddItem used with listboxes, grids Print, EndDoc to print to printer Events Are the stimuli an object can recognize Are listed in the Proc box of the object's code window Some events are nearly universal (e.g., Click) Can be activated by the user (e.g., Click) Some are object specific (e.g., Timer) Event Driven Program Design Most code in Visual Basic is related to an object-event relationship The user or environment activates events in objects, which then activates code Very different than earlier types of program organization techniques Example: Picture1_Click in last week's program Read 'When the user CLICKS on the PICTURE1 control, this will happen.' Common Events Click, Double-click Load, Unload on forms Change on controls that get user input Paint on controls that contain graphical information Getting Help Visual Basic is a complex, growing language with many subtleties Traditional reference books are cumbersome There is a hypertext online help which uses a Windows help engine Help Menu in VB Contents and submenu is good if you need general information Search for Help on - is much more flexible - type in whatever you want help on- a list of similar topics will appear - select the topic you want Keyword Help This is the fastest way to get help Type or point to a keyword that you are having trouble with in a code window Be sure the cursor is somewhere inside that word Hit the F1 key - if the word is a keyword and spelled correctly, a help screen for that word will appear - good for checking syntax General Declarations This is an area that can be used to make comments about your program Example: 'Create a clock that displays a time in a label. 'Place two horizontal scroll bars on the form, 'one that will change the backcolor of the clock label and one 'that will change the forecolor of the clock label. Some New Objects Timer - is invisible at run time - goes 'off' at specified intervals - used to replace loops Timer Properties Interval (in 1000ths of a second) Enabled (True or False) Timer Events Timer - it has 'gone off' New Properties BackColor, ForeColor - attached to most objects FontName - tells which font to use in current object FontSize - tells the size of the current font New Functions QBColor - gets a color using the Qbasic value- uses a number between 0 and 15 - is an easy way to get most common colors Sample Syntax frmSample.BackColor = QBColor (4) Time Time (displays 12 hour clock) Time$ (displays 24 hour clock) Gets the current time from the system clock and returns it as a string Sample Syntax: lblTime.Caption = Time or lblTime.Caption = Time$ End Ends the program Syntax Examples Private Sub Timer1_Timer() 'when the form loads the clock 'should appear in the lblClockFace 'caption area lblClockFace.Caption = TimeEnd Sub outlineVariable Description A container for information (data) A name that refers to a chunk of computer memory Variables have value Can be used in statements rather than a value Value can change Principal Uses Storing information gotten from the user, environment or another source Works with information stored in object properties Can manipulate information (info garage) Type of Variables Computer stores different types of information in different ways Examples: Text - fixed or dynamic length Integers - integers or long integersReal numbers - single and double precision Currency - 8 digits plus four decimal places Variant - computer takes its best guess (risky) Variable Declaration Modes Implicit - simply by using the variable you declare its existence This is used by older forms of Visual Basic Used type declaration characters ($ % & #, etc.) There is no way to check for spelling of variable names - common errors Explicit Declaration Each variable is declared in a DIM statement, using a variable name and the type Example Syntax: - Dim UserName as String Variable should be declared before the code using it in the appropriate code area Can also be set by typing OPTION EXPLICIT in the General area of the form Advantages of using variables Your code is easier to read Misspelling variable names is caught by the complier Makes it easier to set the scope More professional Scope There are different levels where you define variables 1. Procedure 2. Form or general declarations 3. Project level (global) Description Variables can be accessed only in specific parts of the program Prevents errors especially in large programs Allows for compartmentalization of the program Variables are only available to those parts of the program that need it Law Enforcement Scope can be compared to different types of law enforcement: local = same as local police general or form = county sheriff global = state police General (form) Level Variables Are declared in the general area of the form Are available to all objects and code windows attached to the form The value of the variable is accessible to any code in the form NOT the same as a global variable Object Level Variables Are declared in the code window of the specific object Exists only when that code is running If the same variable name is used in a different code window, they are DIFFERENT variables Also called local variables and are preferred when possible Which should you use? If only one object will use the information stored in the variable, make it Object Level If more that one object needs it, make it Form Levelmore later Type Conversion Functions This allows you to convert from one data type to another Val - grabs a numeric value from a string Str$ (Str) converts a numeric value to a string Is frequently used to convert from variant to a more specific type Simple Dialog Boxes Message Box (MsgBox) is a easy way to send a short message to a user Syntax: MsgBox ("String value to send") Example: MsgBox ("Hello World") Or: Dim Message as String Message = "Hello World" MsgBox (Message) Inputbox These are easy ways to get quick input from the user Syntax: VariableName = Inputbox(String value representing questions) Example: Dim UserName as String UserName = Inputbox ("What is your name?") or , Dim Answer as Integer Answer = Inputbox ("What is 5 + 3 ?") If - Then - EndIf Allows for simple evaluations Syntax: IF expression THEN command Example: If Name = "Wally" then MsgBox ("You're a Nerd") If Answer 12 then MsgBox ("Sorry, 5 + 7 = 12") Block for of IF Else EndIF IF expression THEN codeELSE more code END IF Example: IF Ans4 = Total THEN MsgBox ("Very Nice!") ELSE MsgBox ("Too Bad !") END IF outlineConditions Conditions are expressions that can be evaluated as true or false. Conditions are NOT an equation. Conditions usually compare a value to a variable - can also be a variable to a variable. If - Then - Else This is the most basic condition This is used for simple branching Syntax Simple form: IF expression Then command If userName = "Wally" Then MsgBox("Hello, Wally") Block form:IF expression Then codeELSE more codeEND IF Select Case Select Case is used for multiple branching Tests one variable for multiple values Syntax SELECT CASE variableCASE value 1Basic statementCASE value 2Basic statementCASE ELSE Basic StatementEND SELECT Example Dim Year as String Year = InputBox "In which year was 'Gone with the Wind' produced?" Select Case Year Case "1937" MsgBox "WAY too early" Case "1938" MsgBox "A little too early" Case "1939" MsgBox "PERFECT!!!" Case Else MsgBox "Your are WAY off!!" End Select Do..Loop This is used for conditional looping DO and LOOP keywords mark the beginning and the end of the loop. Syntax DO [WHILE, UNTIL, or NOTHING] [Condition for WHILE or UNTIL] code inside loop LOOP [WHILE, UNTIL or NOTHING] [Condition for WHILE or UNTIL] WHILE Condition The loop continues as long as the condition is TRUE The loop ends when the condition is FALSE UNTIL Condition The loop continues as long as the condition is FALSE The loop ends when the condition is TRUE This is the opposite of WHILE Placement of the Condition DO - the condition is evaluated BEFORE the code is run It is possible to skip code Is usually necessary to initialize a sentry variable - a sentry variable is a counter type variable Loop Code runs at least once before condition is checked The initialization often occurs in code Is more commonly used Example: Until at bottom Dim Answer as Integer Answer = 0 Do Answer = Val(InputBox ("What is 2+3")) Loop Until Answer = 5 Example: While at top Dim At_Peace as Boolean At_Peace = True Do while At_Peace = False Launch_Missles(Russia) Loop Example: While at bottom Dim At_Peace as Boolean At_Peace = True Do Launch_Missles (Russia) Loop while At-Peace = False 3 things to consider What is the condition? Do I need the condition at the top or the bottom? Do I want a while or until condition? For/Next Loop This is a simpler and older loop Used for counting You must know how many times you will do the task (either directly or in a variable) Syntax: For counting_variable = 1 to limit [STEP steps] BASIC code?.. NEXT counting_variable Example: Simple counting loop For I = 1 to 10 MsgBox Str (I) NEXT I Example: Counting backwards For I = 10 to 1 Step -1 MsgBox Str (I) Next I Using the counter inside the loop For Xpos = 0 to MyForm.Width Step 100 ImgCar.Left = Xpos Next XPos Other techniques you will need CLS Method Atached to picture boxes and forms Allows you to clear the object Derived from the old CLS command Syntax: ObjectNaame.cls Print method Attached to picture boxes, forms and printer object Allows you to print a value directly to the object Derived from old PRINT command Syntax: ObjectName.Print Value Value can be a string or numeric, direct or variable name outlineVariable Arrays A list of variables, all of the same type, with similar meaning but different values each one having an index number Can be any valid variable Example: Putt-Putt scores Syntax Dim hole(18) As Integerhole (0) = 1hole (1) = 2hole (2) = 3 Initialization Individual numeric array elements are initialized to zero by default You, the programmer can explicitly initialize the array with assignment statements as in the previous slide Bounds versus Index The position number contained within parentheses is called an index Declaring the variable - Dim numbers (5) As Integer - would tell the computer to reserve 6 elements for an Integer array of numbers - the value 5 defines the upper bound (highest value) of numbers - the lower bound of numbers defaults to 0 When an upper bound is specified in the declaration, a fixed-size array is created Uses A variable array frequently used in a for-next loop The upper bound is frequently a constant Used when you want to be able to have multiple values for properties (e.g., the same label used to display three different captions at different times) Used when you are keeping track of a list or table of data (e.g., your grades) Control Arrays Conceptually similar to variable arrays Are an array of controls of the same type and all controls in an array share the same properties as a default (properties can be changed through code individually) All controls in an array share the same code box All events related to a code array automatically pass an Index parameter Using a Control Array Used when several controls need to do the same thing (e.g., color box) Example: you want to store images off-screen for quick access Creating a Control Array Create the first object in the regular way Set the properties of this object ESPECIALLY the name Copy the object, paste it - a dialog box will ask you if you want to create an array Click "YES" and move the new object wherever you want it. Continue this process until you have all you need. Constants Treated much like variables in code except: - the value of a constant cannot change during the execution of the program - a constant cannot be given a new value during the run of the program Uses of a constant A constant would be used to name a number so it is easier to use in code Example: PI = 3.1415927 A constant would be used to refer to a commonly occurring value in a program Example: NumPics = 3 Additional uses If the programmer updates the program to handle more frames, he only has to change the constant definition - this saves time and makes the program easier to read Syntax CONST Identifier = Value Image boxes Are a control to handle pictures and the property of the picture determines what image is shown The picture can be copied to the clipboard, loaded from a disk file or copied from another object The image box automatically resizes itself to the picture size and can be used to scale pictures Special property The image box has a special property - visible that is used to hide pictures "off stage" Syntax: ControlName.visible = True or False True means the control is visible and is the default False means the control is invisible Multitasking as a programming tool Multitasking is the ability to run multiple program simultaneously on the same processor Multitasking is commonly used when defining graphic elements of a visual basic program Visual Basic has limited drawing features of its own but allows use of Windows Opaint or other specialized drawing programs It also allows the programmer to define icons, sound effects, and other elements using specialized tools outlineDesigning Menus Menus should follow Windows standards (be along the top of the screen) Have an option for the user to have quick access to an item (alt + underlined letter, i.e., File), also known as shortcut keys How the menus are seen by VB They are attached to the form and each menu item is a mini control with only a few properties Each menu item has only a CLICKED event it recognizes The menu design window The component "CommonDialog" must be added to the list of tools by choosing Projects from the menu, then Components, and select the Common Dialog option from the list of items available Designing the menu The 'Menu Editor' is located on the horizontal toolbar on the left-hand side This allows you to create an outline of the menu structure, change properties of the menu items The user will see what the developer places in the caption area Placing an & in front of a letter indicates that the next letter will be underlined and used for quick access (&File will show File) Name is like a control name and should use mnuFile naming convention, each menu item MUST have a name The Shortcut This allows you to assign a Control combination or function key to the menu item Checked: tells whether there is a check mark placed next to the item (TRUE or FALSE) Enabled shows whether the user can access the item (TRUE or FALSE) Visible shows whether the item is visible (TRUE or FALSE) Accessing the code Once you have your menu designed, it will appear at the top of your form, all you will need to do is click on the menu item's name to access the code window for the name you have chosen Common Menu Guidelines Items are usually 2-3 items deep, but can be deeper and usually less than 7-10 choices per menu When possible, the first letter should be underlined and be related to a shortcut key Common Dialogs There are already dialog boxes existing in Windows Many commands are used in various types of programs (Save, Open, Font, etc.) Dialog boxes related to these commands are available as common dialogs The Common Dialog Box Control works very differently from most controls The control is NOT visible on the form (similar to the Timer - it's there but you don't see it) The control is 'called' by the use of an action statement or a show method Example: CmDialog1.Action = 3 CmDialog.ShowColor Actions of the Common Dialog Same control can 'call' any of the dialogs depending on the value of the action property ActionType of box

1Open

2Save

3Color

4Font

Methods The common dialog control actions can also be controlled through methods. Many programmers find these easier to remember than use rather than the action property Some methods are: ShowOpenShowSaveShowColorShowFont Example: CmDialog1.Action = 1is exactly the same asCmDialog1.ShowOpen Properties set in design time Filter - this is used in file dialogs to determine how dialog will isolate files Format - .TXT(TextFiles)|.TXT (there is no space on either side of | which is the 'pipe' character This is usually located on the backslash key, sometimes it looks like a broken vertical line Properties changed in run time The properties of a common dialog are used for communication between the user and the programmer Common dialogs DO NOT do actual file manipulation, color changing, or whatever They bring up dialog boxes for the user to select these things and they store the user's choice in the properties of the common dialog object outlineFile Handling Is a method of handling external data Data is kept in FILES on the disk and a program can read and write information from or to these files. The programmer is responsible for controlling the flow of this information Sequential Access Files These work like a cassette tape or VHS tape. You start at the beginning of the tape and listen or watch from beginning to end (if it is a good tape or movie) This method can be slow if there is a large number of records Records can have a variable length This type of file access is useful when a flexible structure is more important than quick access The OPEN Statement Syntax: OPEN filename FOR method AS # filenumber The filename is any valid DOS filename Caution in allowing the user to create the file names Methods for the OPEN Statement INPUT: reads information from an existing file (retrieving existing file for input) OUTPUT: creates a new file, adds information to it, overwrites with new information to an existing file APPEND: adds information to the end of an existing file Choosing a method Usually OUTPUT is used only when creating a new file as it will destroy existing files with the same name APPEND is generally used for output The filenumber Must be an integer, usually 1 or 2 This is unique for each file opened - it tells what file number you want to access Keep this simple The WRITE # statement This is used to write to a file Before you can write to the file, you must have opened the file via OPEN (Output/Append) The Syntax WRITE # FileNumber, Value(s) The FileNumber must match the file number on the OPEN statement The Value(s) would be the direct value or variables separated by commas The INPUT # statement This is used to get data from a file and the file must have been opened via the OPEN statement (Input) The INPUT Syntax INPUT # FileNumber, variable Where the FileNumber is a valid, open file and variables separated by commas The CLOSE statement This statement is used to close the file and release its filenumber The syntax: CLOSE # FileNumber The EOF function EOF (end of file) is a Boolean function - it is either TRUE or FALSE Is TRUE if the program has reached the end of the file and is usually used in DO LOOPS with file handling Syntax and Example EOF (FileNumber) Example: DO..program codeLOOP UNTIL EOF(1) NOT operator This sets a Boolean to its opposite value and is commonly used for check boxes and Boolean properties Example:Text1.FontUnderlined = NOT Text1.FontUnderlined If Font Underlined is true, it will become false, if false it will become true SETFOCUS method This method is used in conjunction with an object and that object receives the focus. Example:Text1.SetFocus By doing this the insertion cursor will appear in the text box. Any subsequent key presses will be processed by the text box On Error Resume Next This is used when you anticipate an error in a procedure, especially in file handling When an error occurs, the program skips to the next line This is only good within the procedure where it is defined outlineModules Description of a module: - they are like separate files on a disk - they are like the code part of a form - no objects are attached - are saved on the disk with a .BAS extension What do they contain? Modules contain record definitions GLOBAL variable declarations Global procedures How are they used? Modules are used to declare GLOBAL variables - use the keyword GLOBAL in place of DIM - can only be used in the general area of a module - otherwise used just like DIM Creation of global procedures Because they are global, they can be called from any form, any procedure in the project It is just like creating a new command Can be used to store a library of useful subprograms (e.g., printing related) Are created by choosing New Module from the File menu or hitting New Module button Scope map Global procedures Are created in the general area of forms or modules In forms, makes a form-level procedure In modules, makes a global procedure Can be called from within code - New command Syntax Sub ProcedureName (Parameters) Creates a new section of the general area Code can be written in this area Parameters "Instant" local variable(s) They don't have to be declared To call a procedure -simply use its name in code Multiple forms To create use New Form on the File menu or New Form button Useful methods - -Show - Hide Show Syntax: FormName.Show 1 This action is modal The FormName is the name of the form you have created in the project Example Second.Show 1 This loads Second into memory if it's not there and shows it to the user Modal switch If you end the show method with a 1, the form will be modal The new form gets focus The next code that is activated is in the form_load procedure of the second form The control reverts to the original form after the second is closed If you do not put a 1 at the end, the form shows up, but does not get the focus The control of the program moves on to the next line of code in the first form Hide Syntax: FormName.Hide Example: Second.Hide This hides the named form and the control reverts back to the procedure that showed the form Warning! Don't hide ALL the forms in a project! Startup form One form must be designated as the startup form By default this will be the first form created To change this, use the Project dialog under the Options Menu outlineDatabases Sequential access is used when records with be of differing length Allow more flexibility, but more difficult programming Require programmer to keep tack of the record number Can use custom variable types Random Access Individual pieces of data may be referenced without having to process sequentially all of the information that precedes that data in the file. Random Access Files The simplest is to require that all records in a file are of the same fixed length Using fixed length makes it easy for a program to calculate the exact location of any record relative to the beginning of the file Data can be inserted, updated or deleted and each random-access file will have one of these three access types User defined TYPES A compound variable that combines many standard variable types Usually refers to a RECORD in a database and is also called a RECORD variable Usually fixed length which is ideal for ramdom-access The TYPE statement TYPE newType var1 as datatype var2 as datatype var3 as datatypeEND TYPEGLOBAL variable AS newType Description newType is your custom data type Usually ends in TYPE (by our convention) This is NOT a variable. It is a new variable TYPE (like string, integer, etc.) var1, var2, etc. are regular variable names Datatype refers to standard variable types (string, integer, single, etc.) Example Type AddressTypeName as String * 30Phone as String * 15Add as String * 50End TypeGlobal Address as AddressType Use of record (compound) variables Are much like Object Oriented Programming syntax Variable.Record (e.g., Address.Name = "Andy") Files (description) Must be fixed-length records for random-access file More like a CD player. Individual records can be accessed directly Frequently use custom data types OPEN statement OPEN filename for RANDOM AS #filenumber LEN = LEN(RecordVariable) Example:OPEN "A:\Address.dat" for Random as #1 LEN = LEN (Address) The same open statement is used for reading, writing, and appending. PUT statement Is used to Copy information from a variable to the file The filename must have been opened with an OPEN for RANDOM command Syntax: PUT # fileNumber, RecordNumber, RecordVariable Example: to place the current contents of the address variable to the 4th position in the file:PUT #1, 4, Address To place the current contents of the address variable in the position in the file contained in the recNum variable:PUT #1, recNum, Address GET statement Identical to the PUT statement except it transfers information FROM the database TO a variable Filename must have been opened with an OPEN for RANDOM command Syntax: GET # FileNumber, RecordNumber, RecordVariable Note: Filename must have been opened with an OPEN for RANDOM command Example: To place the current contents of the 4th position in the file to the address variableGET #1, 4, Address Notes on use of GET and PUT Both are frequently put in separate procedures to simplify use Both require an OPEN statement before use and a CLOSE statement after Sample GET procedure (assumes Record variable called Address) Sub GetAddressOPEN FileName for Random as #1 Len = Len(Address)Get #1, RecNum, AddressClose #1TxtName.text = Address.NameTxtPhone.text = Address.PhoneTxtAdd.text = Address.AddEnd Sub Notes: The previous code assumes access to variables FileName, RecNum and Address (the Record Variable) Notice that we first GOT the variable from the file, then copied it to the form This code would probably be at form-level PUT procedure A similar PUT procedure would: Copy the fields from the form objects to the variable Open the file, put the variable to the file Close the file Parallel Arrays Loads all records into a record array (record variable) or a series of arrays in memory Provides fast execution Loads from the disk only once Only allows a number of records that will fit into memory at one time Information is volatile until saved. Linked Lists Each record contains a field that points to the next record Done by adding extra field(s) in custom variable type There is a Pointer field containing the record number of the next/previous record in the field Allows for convenient sorting, but slow searching Double-linked lists Binary tree Indexing A separate file or array is maintained comparing the record number to the position in a sorted list Various indices can be created sorting by different criteria This can be easily created with sorted list box technique in Visual Basic Relational databases Information is contained in more than one table of data One table may track personnel, another may track payroll Links between tables Allows flexibility Sorting algorithms Bubble sort - slow but unwieldy - easy to write Shell sort - more efficient but more complex Quick sort - among the best overall techniques, uses recursion outlinePurpose of the class Who is it for? What we are learning Programming essentials Specific languages Emphasis on concepts Practical applications - educational - scientific - business settings Why program? History Usefulness now Engineer analogy Hardware information Disk - floppy 1.44 meg - you may want to have 3 available - one to turn in, two to work on Computer requirements Visual Basic v6.0 Solving problems with STAIR State the problem Tools Algorithm Implementation Refinement History of programming Sumerian Algorithms Abu Ja'far Muhammad ibn-Musa Al-Khowarizimi (algorithm is derived from the last name) Pascaline 1659 Analytical Engine 1834 Lady Ada Birth of programming languages Eniac - cords and wires Grace Hopper and A0-first compiler (first bug - origin of debugging) Higher level languages Fortran - first practical higher level language COBOL - business oriented PASCAL - teaching language BASIC - hobbyist's language QuickBASIC - BASIC comes of age OOP - object oriented programming (C, PASCAL) Next generation - Hypertalk, Visual BASIC Windows-general characteristics GUI, graphically based Multiple ways to do things, User-driven Device Independence, Event oriented Mouse is critical, Multi-tasking Programming differences-DOS Programmer in control, user interface up to programmer User has few options - computer 'train' the user Programmer must anticipate user's wishes Procedural program design, programmer directly responsible for all device control Programming differences-WINDOWS User in control OOP - object oriented program design Standardized user interface Generally harder to program, easier to use Visual Basic Guided Tour Parts of the VB Editor Menu bar, Tool bar, Tool box, Project window, Properties box Using menu bar to show, hide other components Naming a form Click on the form to select it Click on the properties box or right-click on the form Click on the NAME property to select it (scroll through the list to locate) Highlight editing part of the properties box - change name to MyFirst Notice change in the properties box - caption of form has not changed Changing the form's caption Use the same procedure to change the form's CAPTION property to {your name}'s First VB Program Examine other properties of the form, but do not change them randomly Adding a picture box Show the toolbox if hidden Click on the Picture box icon (the cactus picture) Drag small area on the form - this is your picture box Change shape by using the '"handles" Picture box Naming convention - pic, so name something like picBlue Change background color of the box Double-click on the BackColor property Choose a color for your box from the palette Adding some code to Picture box Double-click on the picture box - this brings up the code window First, decide on the algorithm - then implement it Some concepts Object oriented syntax - OBJECT.PROPERTY - sometimes FORM.OBJECT.PROPERTY - note the periods and lack of spaces Variable = value Read "Variable gets value" NOT equality For our purposes, an object property is a variable Saving the program VB has TWO different files for each program:Form has a .FRM extension - contains description of the form, objects and codeProject has .VBP(Visual Basic Project) extension - essentially has a list of the forms in the program Use the Disk icon to save This is the safest way to be sure everything is saved Look at the default name given and ALWAYS use the same extension If you are confused, use NO extension at all VB will guess better than you Test the program Press the Play button on the toolbar - you will see your program running Click on the form outside the box, nothing should happen Click inside the box, the window should change colors Hit the stop button to return Save the program Test and save the program

HAVE FUN!