advanced gis functions procedures arrays and collections l.
Download
Skip this Video
Loading SlideShow in 5 Seconds..
Advanced GIS: functions,Procedures, Arrays and Collections PowerPoint Presentation
Download Presentation
Advanced GIS: functions,Procedures, Arrays and Collections

Loading in 2 Seconds...

  share
play fullscreen
1 / 35
fergus

Advanced GIS: functions,Procedures, Arrays and Collections - PowerPoint PPT Presentation

177 Views
Download Presentation
Advanced GIS: functions,Procedures, Arrays and Collections
An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Advanced GIS:functions,Procedures, Arrays and Collections Fall 2003 VB - III

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

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

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

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

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

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

  8. Connect File>Save with Common Dialog • In Code Editor, type in the following code associated with mnuFileSave_Click() • dlgFile.ShowSave VB - III

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

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

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

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

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

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

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

  16. Variable Scope VB - III

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

  18. Option Explicit • Implicit Declaration - in VB, if no declaration for variables. Try the following code • myVariable = 5 • myVariable = myVariable + 5 • MsgBox myVariable VB - III

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

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

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

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

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

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

  25. Arrays - used to store a series of elements that usually contain related information • Fixed-size array • Dynamic array • Multi-dimensional arrays VB - III

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

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

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

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

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

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

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

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

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

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