360 likes | 660 Views
Advanced GIS: functions,Procedures, Arrays and Collections. Fall 2003. Functions and subprocedures. Functions - consist of code that does something specific and then return a value to the part of the program that called it. For example, the Sin() function.
E N D
Advanced GIS:functions,Procedures, Arrays and Collections Fall 2003 VB - III
Functions and subprocedures • Functions - consist of code that does something specific and then return a value to the part of the program that called it. For example, the Sin() function. • Subprocedures - don’t return results, eg. the “Unload” method. So far, the code we wrote are for event subprocedures. When a command button named “Command1” is pressed, Visual Basic runs the Command1_Click() event subprocedure. Subprocedure usually does something, like changing the display, but it doesn’t tend to pass anything back to Visual Basic VB - III
Creating a sub procedure • Two ways to add sub procedure • 1) Use the Add Procedure dialog box or • Open the Code Editor window and go to Tools > Add Procedure. Type in Name of the procedure and make sure Private scope is checked and click OK to continue • 2) Directly define a procedure in the Code Editor window - type in code for a procedure and end with End Sub VB - III
Call Procedure • Using “Call Procedure_Name” to call procedure. You may directly use Procedure without calling procedures, but it’s not recommended. Private Sub cmdCalculate_Click() intMyNumber = InputBox (“Input your number”) Call SquareNumber End Sub Private Sub mnuToolsCalculate_Click() SquareNumber End Sub Private Sub SquareNumber() lblAnswer.Caption = intMyNumber * intMyNumber End Sub VB - III
Passing Arguments to procedures Private Sub SquareNumber(intNum As Double) lblAnswer.Caption = intNum * intNum End Sub Private Sub cmdCalculate_Click() intMyNumber = InputBox (“Input your number”) Call SquareNumber(intMyNumber) End Sub Exercise: create a sub procedure with two arguments for calculating area of a rectangle Private Sub Area(x as single, y as single) lblAnswer.Caption = x * y End Sub Private Sub cmdCalculate_Click() ‘need to declare width/height width = Inputbox (“Input width of a square”) height = inputbox (“Input height of a square) Call Area(width, height) End Sub VB - III
Let’s create a window menu using Menu Editor • Add a new form (Project > Add Form) • Go to Tools > Menu Editor and create a two-layer menu as shown on right VB - III
Common Dialogs • Insert Common Dialogs from Project > Component > Microsoft Common Dialog • The following are the functions available: • Open file- ShowOpen • Save File - ShowSave • Color - ShowColor • Font - ShowFont • Print - ShowPrinter • Help - ShowHelp • Name this common dialog as “dlgFile” VB - III
Connect File>Save with Common Dialog • In Code Editor, type in the following code associated with mnuFileSave_Click() • dlgFile.ShowSave VB - III
Exercise • Add Two menus to your SlideShow(HW8) program: File and Tools • Add Save As, and Exit on File menu and SlideShow on Tools menu. (mnuFile, mnuFileSaveAs - Ctrl+S, mnuFileExit, mnuTools, mnuToolsSlideShow) • Add Microsoft Common Dialog Control 6.0 and name it as “dlgMain” (under munFileSaveAs_Click() ) dlgMain.FileName = lstSlides.Text dlgMain.ShowSave If dlgMain.FileName <> “” Then SavePicture imgPicture, dlgMain.FileName End If • ‘SavePicture requires two arguments, first-the picture or image control from which the graphic file is to be created. The second is the full path to the location where the picture file is to be saved. VB - III
use code “Unload Me” for mnuFileExit (and dlgFile.ShowOpen to associate with Open, if Open is under File) • mnuToolsSlideShow_Click() - type a msgbox “SlidShow has not been implemented yet” with vbExclaimation • run this program and save file to different location with different file names VB - III
Public or Private • Public subprocedures are declared like this Public Sub <subprocedure name> Public Function <function name> As <return type> • A public routine can be accessed throughout the program but a private can only called in the same Form or Module • Advantage of using Private use less memory, code protected within one corner, and names used over and over VB - III
Passing arguments to procedures • If a procedure requires arguments, they are passed to the procedure, when the procedure is called. Let’s create a Sub called SquareNumber with argument and one command button, one text box and a label for showing the answer. Private Sub SqureNumber (intNum As Double) lblAnswer.Caption = intNum * intNum End Sub • Arguments have to be supplied to run this procedure. Let’s modify cmdCalculate Private Sub cmdCalculate_Click() Call SquareNumber (txtNum.text) End Sub VB - III
ByRef or ByVal • Argument s can be passed either by value or by reference. Passing by value- a copy of the variable is passed to the sub procedure. If the variable is changed in the sub procedure, the original variable in the calling procedure is not affected. If an argument is passed by reference, changing the argument in the sub procedure will permanently change the argument in the calling procedure. ByRef is default, if not specified Dim X As Integer X = 5 Call aSub(X) MsgBox “X = “ & X Private Sub aSub (ByVal Y As Integer) Y = 6 End Sub Try ByRef VB - III Change ByVal to ByRef and see the differences
Built-in functions • String, numeric, date and time, financial functions. • Commonly used String functions • LCase/UCase: converts to L/U case • Len: return length of string • Left/Right/Mid: return specified number of cha. form left/right/middle side of a string. • Replace: replace one or more occurrence of a string inside another • LTrim/RTrim/Trim: removes spaces from the beginning (end)(both ends) of a string. • InStr/InStrRev: returns the position of the first(last) occurrence of one string within another • Join: return a string created by joining a number of substrings contained in an array. VB - III
Numeric/Date/Time • Abs/Sin/Cos/Tan/Atn(arctangent)/Exp/Log/ Sqr/Sgn(sign of a number)/Rnd (random number)/Int,Fix (integer portion of a number) • Date-current system date • DateAdd- add specified interval to a date • DateDiff - differ of two specified dates • .. • .. VB - III
Variable Scope VB - III
Static statement - to preserve the values of procedure-level variables, use Static VariableName [As data type] • used to maintain the values of variables between calls of the procedure. • Try this Private Sub Command1_Click() Static intNum As Integer intNum = intNum + 1 MsgBox intNum End Sub Try to run these code several times, the increment of intNum can be shown in Static but not Dim • Private Sub Command1_Click() • Dim intNum As Integer • intNum = intNum + 1 • MsgBox intNum • End Sub VB - III
Option Explicit • Implicit Declaration - in VB, if no declaration for variables. Try the following code • myVariable = 5 • myVariable = myVariable + 5 • MsgBox myVariable VB - III
Function procedures - return values which determines data type of functions • Return a value from a function by assigning it to the name of the function itself. Basically, the function is treated as though it were a variable. • In slides 4/5, the SqureNumber sub can only change the lblAnswer.Caption. If a function is in place such as the follows: Private Function SqureNumber (intNum As Double) As Double SquareNumber = intNum * intNum End Function Private Sub munToolsCalcualte_Click() Dim intMyNumber As Double intMyNumber = txtNum.Text lblAnswer.Caption = SqureNumber (intMyNumber) End Sub VB - III
Multi-form projects • Most projects need more than one form. For instance, login form, splash form and about form. • To add a new form to a project, choose Add Form from the Project menu or right-click in the Project Explorer window. • Form can be referred as “Me” by procedures within the form, and other forms must be referred to by their names. • If a project contains more than one form, a startup form must be declared in the Project Properties dialog box, accessed from the Project menu. (go to Project>Project Properties...) • If you want the application to start without any form initially loaded (e.g., retrieve data ->display one of the form depending on the contents of the data file), then create a Sub procedure called Main in a standard module and select Sub Main as the Startup Object. VB - III
Manage Forms Tasks Methods/Statements Load/Not Display Load Statement Load&Dispaly Show method Display a loaded form Show method Hide/Not unload Hide method Hid&Unload Unload Load frmMain ‘ or frmMain.Show frmMain.Hide ‘ or Me.Hide Unload frmMain ‘or Unload Me, code portions still exist Set frmMain = Nothing ‘completely terminate the form and ‘reclaim memory VB - III
Modal/Modeless Forms • Most of dialog boxes in VB are modal. Only one form can be modal on the screen at one time. When a modal form is displayed, the application beeps if the user clicks outside the form. • Modeless form- allows the user to switch to another form or dialog box • With the style argument vbModal or vbModeless, the Show method displays a modal or modeless form. If you do not specify the style argument, the form will be modeless. For example: • ‘Modal form • frmMain.Show vbModal • ‘Modeless form, the default • frmMain.Show vbModeless VB - III
Standard modules • No GUI, no form, only code. • Public procedures shared by multiple projects, avoid referencing form-specific controls, which can be passed as arguments to the general procedures of the standard module. • To call the procedure from outside the standard module, directly refer to procedure’s name, if it is unique, otherwise, you need the module name as the prefix. To call procedure within own std module, simply refer to the procedure name. • Save the std module with a unique name and .bas file extension in the same directory where the project file is saved. VB - III
Practice • Create a new project with form. • Add standard module from U:\4850_5850\ArcObjects\aml_func.bas by checking on Project>Add Module and navigate to this directory. • Add a command button(cmdParse, Caption:Parse), textbox (txtInput) and type in code under cmdParse_Click() Private Sub cmdParse_Click() Dim strMyArray() As String ParseStringR txtInput.Text, strMyArray MsgBox strMyArray(0) End Sub ‘try single quote VB - III
Arrays - used to store a series of elements that usually contain related information • Fixed-size array • Dynamic array • Multi-dimensional arrays VB - III
1-D fixed array Dim My1DFixedArray(4) As String ‘declare array with 5 elements My1DFixedArray(0) = “Heart” ‘assign value My1DFixedArray(1) = “Club” My1DFixedArray(2) = “Spade” My1DFixedArray(3) = “Diamond” My1DFixedArray(4) = “Club” MsgBox My1DFixedArray(2) ‘retrieve ‘Specify upper/lower bound Dim My1DFixedArray(0 to 4) As String Dim My1DFixedArray(1 to 4) As String VB - III
Dynamic Arrays - number of elements to be stored is not known ahead of time Dim DynArray() As String Dim X As Integer X = InputBox (“Enter the number of elements in the_ array: “) ReDim DynArray(X-1) Slide1 Slide2 Slide3 Slide4 .... .... 0 1 2 3 Allow programmer to manage memory more efficiently than fixed arrays VB - III
ReDim/Preserve/Erase • The size of array will be specified at run-time with keyword ReDim and the memory for the array is then allocated. You can change size of dynArray anytime with ReDim statements, but the original values contained in array are lost once encountering ReDim. Use keyword “Preserve” to preserve values. • ReDim Preserve DynArray (UBound(DynArray) + 1) ‘this add one element more but preserve previous values • Use “Erase” to deallocate memory and ReDim to reallocate memory. e.g Erase DynArray VB - III
Multi-dimensional arrays Path(0) Date(1) Second(2) Title(3) Slide(0) C:\temp 1/30/89 5 Slide show Slide(1) U:\4850 3/19/02 4 Rex Slide(2) E:\temp 3/20/01 6 Trees Option Explicit Dim Slide() As String Private Sub Command1_Click() ReDim Slide(0 to 3, 0 to 1) ‘Assign value Slide(col,row) = value Slide(0,0) = “C:\temp” Slide(0,1) = “1/30/89” Slide(0,2) = “5” Slide(0,3) = “Slide Show” Slide(1,0) = “U:\4850” ‘Add more data ReDim Preserve Slide(3, UBound (Slide,2) + 1) VB - III
Exercise - work with 2-D dynamic arrays • Create a new Form(frmGrades, “Enter Grades”), add two labels(lblStudentName, “Student Name”; lblLetterGrade, “Letter Grade”), 2 text (txtStudent, “”; txtGrade, “”), 1 commandbox (cmdApply, “Apply Grade”, Default = True), Horizontal Scroll Bar (hscStudent, Max=0, Min=0) • The application will store students’ names and grades in any array (dynamic). Because the values in the array will need to be used in 2 different procedures. Variables have to be declared at the form level. Dim Score() As String • Store student names in a 2-D dynamic array: Declare a Static variable Number As Integer (maintain the number of students between procedure calls) VB - III
Grade Private Sub cmdApply_Click() Static Number As Integer ReDim Preserve Score(1, Number) Score(0, Number) = txtStudent.Text Score(1, Number) = txtGrade.Text hscStudent.Max = Number hscStudent.Value = Number Number = Number + 1 End Sub 2-D Array txtStudent.text stored in Score’ first column, and txtGrade in 2nd column hscStudent.Value: indicate where the slider of the horizontal scroll bar is located and act as the index for the Score array. When you move the scroll bar slider, the Value property is changed, and a different element in the Score array is retrieved and displayed in txtStudent Private Sub hscStudent_Change() txtStudent.Text = Score(0, hscStudent.Value) txtGrade.Text = Score(1, hscStudent.Value) End Sub VB - III
Collection -an object that does not have a graphic component, dynamically grows and shrinks • Dim MyCollection As New Collection • You can use four methods: Add, Remove, Count, and Item (Variant is the data type for storing different data type) • Key MyCollectioin Index 1 2 3 4 “Hello” 3.14159 2/7/02 Slide1 Key “strHello” “Pi” “dt2/7/02” “slide1” It’s safer to use the key strings to identify the items, why? VB - III
Colleciton - 2 • ‘Add NewItem w/o key at the end of the collection • MyCollection.Add NewItem • ‘Add NewItem w/ key “myNewItem” at the end of the col. • MyCollection.Add NewItem “myNewItem” • Remove using Index or Key. Index starts from 1 not 0. • MyCollection.Remove 5 ‘Remove the fifth item • MyCollection.Remove “myNewItem” ‘remove using key • To Change an item, add new item first before or after the old item, then remove the old one. e.g. change 2/7/02 to 3/20/02 • MyCollection.Add “3/20/02”, “dt3/20/02”,3 • MyCollection.Remove 4 ‘ or Remove dt2/7/02 • Set MyCollection = Nothing ‘clear collection VB - III
Looping through Collection • 1) For Each... Next and 2) For....Next Dim Thing As Variant For Each Thing In MyCollection ‘ for each is more efficient ‘than for next. lstName.AddItem Thing Next Set Thing = Nothing ‘ set variant to nothing will recollect ‘memory Dim I As Integer For I = 1 to MyCollection.Count lstName.AddItem MyCollection.Item(I) Next I VB - III
Homework 9-1: 30 points, due on 11/6/03. • Work on your previous homework, if you don’t have a good vbp file, copy it from data_center\hw9-data folder. • See demo for the tasks to be completed. • See link on the webpage to get detailed description of the homework VB - III