370 likes | 521 Views
CP2030 VBFC Lecture 4. Back To Index Iteration - Looping Arrays Sliders Arrays of user defined types Controls - Frames, Radio Buttons, Check Boxes Controls - List, combo, picture, image, timer, shape Data Validation. Looping Constructs. Looping constructs in Visual Basic:
E N D
CP2030 VBFCLecture 4 Back To Index • Iteration - Looping • Arrays • Sliders • Arrays of user defined types • Controls - Frames, Radio Buttons, Check Boxes • Controls - List, combo, picture, image, timer, shape • Data Validation
Looping Constructs • Looping constructs in Visual Basic: • For...Next Loop • used to perform a statement (or set of statements) a fixed number of times • you should know how many times you want to perform the statements inside the loop before you reach the loop • Do...Loop • used to perform a statement (or set of statements) one or more times, depending on whether the condition at the top or bottom of the loop is true or false
For...Next Loop Construct • In C : for (count=startvalue; condition; increment) { statements; } • In VB ::Students to add syntax Count can be any of these types: • Integer or Long, Single or Double, Currency
For...Next Loop Step • We can also specify the step size and count backwards:Sub Command1_Click ()Dim iCount As IntegerFor iCount = 100 To 0 Step -10Print "iCount = "; iCountNext iCountEnd Sub • Unless a Step is specified the For loopwill increment by 1 each time • You should never change the value ofthe control variable inside the For loop
Do...Loop Forms • There are a number of forms of the Do...Loop: General form : Do [{While / Until}] condition statements exitdo ‘can be used to terminate the loop Loop same as break in C Do statements exitdo Loop [{While/Until}] condition
Do While condition….Loop 1. Repeat while loop DoWhileconditionstatementsLoop • Tests condition first • Do While executes whilst the condition is True, terminating when it becomes False • Statements within looping structure are only executed if the condition is true
Do...Loop Until condition 2. Repeat Until Loop Do statementsLoop Until condition • Loop will always execute at least once. • Loop executes Until the condition is True,
Examples (1) Students to add example
Question • Write the equivalent C structures for : (a) the repeat while loop (b) the repeat until loop
Answers Students to add answer
Refresh/DoEvents • While in a loop VB directs all the computers processing to calculations in the loop - can cause problems. • Refresh forces the object to be refreshed eg. Lable1.Caption.Refresh • DoEvents forces checks on input from the user. eg. DoEvents • Consider For inum=1 to 1000 label1.Caption=Str$(inum) Next
Arrays - Defining an Array • Arrays can be delared for any type using the standard declarations :Dim - at module, form or procedure levelGlobal - at module levelStatic - at procedure level • Delaring the size of the array Students to add examples An array variable can be declared in a code module, a form, (or a procedure see later notes)
Accessing an Array • Array name and the element number are used • Dim asName(5) As StringasName(2) = “Pete”asName(3) = “Lucy”Text1.Text = asName(4) asName (1) “Jane” (2) “Pete” (3) “Lucy” (4) “Dave” (5) “Ian”
Array Bounds & Option Base • Arrays have a lower address or lower bound, and an upper address or upper bound • We can alter the default lower bound by using Option Base in the general declarations section of a form or module • Option Base can be set to either 0 or 1 • Option Base 0 ‘sets the lower bound to 0 • Option Base 1 ‘sets the lower bound to 1 • Dim asName(5) As String Option Base 0 asName 0 1 2 3 4 Option Base 1 asName 1 2 3 4 5
Explicitly Stating Array Bounds • We can just declare how many elements we want in our array and Visual Basic will set them up using the Option Base setting: Dim asName(5) As String • We can however state explicitly the lower and upper bounds that we want for the arrayDim asName(5 To 9) As String Option Base 1 asName 1 2 3 4 5 asName 5 6 7 8 9
Using Arrays in Applications • Let’s consider a simple application which stores up to 5 names: In the form’s general declarations: Option Base 1 Dim asNames(5) As String Sub Command1_Click () Dim iPos As Integer iPos = Val(Text1.Text) If (iPos>=1) And (iPos<=5) Then asNames(iPos) = Text2.Text Else Text2.Text = "Error" End If Text1.SetFocus End Sub Sub Command2_Click () Dim iPos As Integer iPos = Val(Text1.Text) If (iPos>=1) And (iPos<=5) Then Text2.Text = asNames(iPos) Else Text2.Text = "Error" End If Text1.SetFocus End Sub
Multi-Dimensional Arrays • Visual basic will allow us up to 60 dimensions! • What about a three dimensional chess board?Dim asBoard(1 To 8, 1 To 8, 1 To 8) As StringasBoard(1,4,3) = “White Knight” • We would advise you not to use too many dimensions, otherwise you will become confused • Best idea is only to use multi-dimensional arrays where they map clearly to the real-world
Clearing Arrays • To clear a complete array you can use the Erase command:Students to add statement • This resets all fields to their ‘null’ values
Dynamic Arrays • Array size is allocated on demand • In the declaration Section:DimasNames() As String • Within a procedure:ReDimasNames(10)orReDim PreserveasNames(15)
Finding Array Boundaries • To find the bounds of a single dimension array we can use: iLowerBound =LBound(asNames ) iUpperBound =UBound(asNames ) • To find multi-dimensional bounds:Students to add statement
Question - Good Practice • Why is the following consider good practice? Const NOOFSTUDS = 30 Dim Ages(NOOFSTUDS) As Integer For icount=1 to NOOFSTUDS iTotAges = iTotAges + Ages(icount) Next icount
Data ValidationControls - Scroll Bars • There are two types of Scroll Bars Vertical & Horizontal • Main properties to set are: Max Min SmallChange LargeChange • Property usually retrieved is Value • The events usually processed are Change or Scroll • Change: when the position has changed message is received • Scroll: when the thumbbar moves the message is received
Question - arrays of records + Scroll bars • Telephone Data entered into the text boxes is to be written into a UDT array at an index given by the value of a scroll bar. • A scroll bar change event displays the data stored in the UDT array at the index given by the scroll bar value. • Show code
Controls: Option (Radio) Button • A Radio Button is one of thecontrols that can be used ona group frame • The property that we are usuallyinterested in is Value Option1.Value = FALSE Option1.Value = TRUE • Grouped Radio Buttons are mutually exclusive • Can process on an Option Click event or wait for a command event • A Click event is automatically generated if you assign a value to the Value property of an option from within a program
Controls: Radio Button Example Usage • Checking which option is selected:Sub Command1_Click ()If Option1.Value Then Label1.Caption = "Option1 Selected"ElseIf Option2.Value Then Label1.Caption = "Option2 Selected"ElseIf Option3.Value Then Label1.Caption = "Option3 Selected"Else Label1.Caption = "No Options Selected"End IfEnd Sub
Controls: Check Box 1 • A Check Box is another control that can be used on a group frame: • Check Boxes can be control arrays Check1.Value = 0 ’unchecked Check1.Value = 1 ’checked
Controls: Group Frame • Frames can be used to group sets of controls, both visually and programmatically: • The Click event can be used • When you place certain new controls on top of the frame they are automatically grouped together • If controls are not on a frame they are grouped on a form • Radio Buttons can be control arrays Group Frame Control
Controls: Check Box 2 • The code behind the Show Checked command button would be:Sub Command1_Click ()‘clear the label caption Label1.Caption = ""‘add checked options to the labelIf (Check1.Value) Then Label1.Caption=Label1.Caption+"Check1 Checked"+Chr(13)End IfIf (Check2.Value) Then Label1.Caption=Label1.Caption+"Check2 Checked"+Chr(13)End IfIf (Check3.Value) Then Label1.Caption=Label1.Caption+"Check3 Checked"+Chr(13)End IfEnd Sub
Controls : List and Combo Boxes • Used to select item(s) to be processes. • Combo boxes open up when selected • Combo boxes have an entry/edit area
List Box • A list box can be used to display & select items, it can be sortedItems are stored in an array starting at index 0 • Useful Methods:Students to add methods
List Box Useful Methods 1 • AddItem adds the item specified to the List Box List1.AddItem “Item Text” • RemoveItem removes the item specified from the List Box List1.RemoveItem 1 • Selected indicates if the specified item is currently selected List1.Selected(1) • ListIndex indicates the first selected item in the List Box iSelItem = List1.ListIndex
List Box Useful Methods 2 • Clear clears all entries from the List Box List1.Clear • ListCount indicates how many items are currently in the List Box List1.ListCount • List is the array containing each of the items that are currently in the List Box Label1.Caption = List1.List(iCount) • Click is the event that is normally processed by the programmer
Combo Box • A combo box is like a list box that only displays the currently selected item, it drops down to allow selection, it can be sorted Items are stored in an array starting at index 0 • Useful Methods:Students to add methods
Comparing List box & Combo box Combo box List box • Occupies several lines on form at all times • Can select only from entries shown • Can select several items • Can display list in multiple columns • Occupies only one line on form when not in use. Drop-down list appears when in use. • Can select from entries shown, or type in another value • Can select only one entry • Can display only one column
Question • Write a section of code to add items to a list box under program execution - take the items from a text box. • Provide a count of the number of items in the list box • When an item is selected from the list box copy the item to a label box.
Picture, Image, Shape • Students to write notes on the above heading.