660 likes | 923 Views
Chapter 5. Lists, Loops, Validation, and More. Introduction. Chapter 5 Topics. This chapter covers the Visual Basic looping statements Do … While Do … Until For … Next It also discusses the use of List Boxes Combo Boxes
E N D
Chapter 5 Lists, Loops, Validation, and More
Chapter 5 Topics • This chapter covers the Visual Basic looping statements • Do … While • Do … Until • For … Next • It also discusses the use of • List Boxes • Combo Boxes • As well as presenting some properties and events used for user input validation
Section 5.1Input Boxes Input Boxes Provide a Simple Way to Gather Input Without Placing a Text Box on a Form
Format of the InputBox Function • Prompt - message to the user (required) • Title - text for the box's title bar • Default - default text for user's input • Xpos - X coordinate for the box's position • Ypos - Y coordinate for the box's position • Square brackets around Title and following arguments indicate these are optional InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos])
Sample InputBox Usage strUserInput = InputBox("Enter the distance.", _ "Provide a Value", "150") • If the users clicks OK without entering a value, 150 will be assigned to strUserInput due to the default value
Xpos, Ypos, and Twips • Xpos specifies the distance from the left of the screen to the left side of the box • Ypos, from the top of the screen to the top of the box • Both are specified in twips • One twip is 1/440th inch
Section 5.2List Boxes List Boxes Display a List of Items and Allow the User to Select an Item From the List
ListBox Items Property • This property holds the entire list of items from which the user may choose • The list values may be established at run time or as part of the form design • To set list values in the form design: • Select the list box in the Design window • Click on ellipses button for the Items property • This property is a collection, a list of values • Type each value on a separate line
ListBox Items.Count Property • This property holds the number of items that are stored in the Items property • Example of use: • The number of items in the list can be assigned to an integer variable If lstEmployees.Items.Count = 0 Then MessageBox.Show("The list has no items!") End If numEmployees = lstEmployees.Items.Count
Item Indexing • The Items property values can be accessed from your VB code • Each item value is given a sequential index • The first item has an index of 0 • The second item has an index of 1, etc. • Example: name = lstCustomers.Items(2) ' Access the 3rd item value
Index Out of Range Error • The index of the last item is always list.Items.Count-1 • Reference to an index greater than Count-1 or less than zero throws an exception • An exception handler can trap this error • The variableex captures the exception thrown Try strInput = lstMonths.Items(n).ToString() Catch ex as Exception MessageBox.show(ex.Message) End Try
ListBox SelectIndex Property • Use the SelectIndex property to retrieve the index of an item selected by the user • If no item is selected, the value is set to -1 (an invalid index value) • Can use SelectIndex to determine if an item has been selected by comparing to -1 • Example: If lstLocations.SelectedIndex <> -1 Then location = lstLocations.Items(lstLocations.SelectedIndex) End If
ListBox SelectedItem Property • Instead of using the SelectedIndex property as follows: • The SelectedItem property can be used to retrieve a selected item value as shown If lstMonths.SelectedIndex <> -1 Then month = lstMonths.Items(lstMonths.SelectedIndex) End If If lstMonths.SelectedIndex <> -1 Then month = lstMonths.SelectedItem.Value) End If
ListBox Sorted Property • Sorted is a boolean property • If true, causes the values in the Items property to be displayed in alphabetical order • If false, values in the Items property are displayed in the order they were added
ListBox Items.Add Method • Items can be added to the end of a ListBox list in your VB code using the Add method • Format is ListBox.Items.Add(Item) • ListBox is the name of the control • Item is the value to add to the Items property • Example: lstStudents.Items.Add("Sharon")
ListBox Items.Insert Method • Items can be added at a specific position of a ListBox in VB code using the Insert method ListBox.Items.Insert(Index, Item) • Index specifies position where Item is placed • Index is zero based similar to SelectedIndex property • Items that follow are “pushed” down • Example inserting "Jean“ as the 3rd item lstStudents.Items.Insert(2, "Jean")
ListBox Methods to Remove Items • ListBox.Items.RemoveAt(Index) • Removes item at the specified index • ListBox.Items.Remove(Item) • Removes item with value specified by Item • ListBox.Items.Clear() • Removes all items in the Items property • Examples: lstStudents.Items.RemoveAt(2) ‘remove 3rd item lstStudents.Items.Remove(“Jean”) ‘remove item Jean lstStudents.Items.Clear() ‘remove all items
Other ListBox Methods • ListBox.Items.Contains(Item) • Returns true if Item is found in the collection • ListBox.Items.IndexOf(Item) • Returns an integer with the index position of the first occurrence of Item in the collection • Examples: • Tutorial 5-1 provides more examples of ListBox controls, methods and properties blnFound = lstMonths.Items.Contains(“March”) intIndex = lstMonths.Items.IndexOf(“March”)
Section 5.3The Do While Loop A Loop Is Part of a ProgramThat Repeats
Repetition Structure (or Loop) • Visual Basic has three structures that allow a statement or group of statements to repeat • Do While • Do Until • For...Next
Do While Flowchart • The Do While loop • If the expression is true, the statement(s)are executed • Expression is thenevaluated again • As long as the expression remains true, the statement(s) will continue to be executed Expression statement(s) True False
Do While Syntax • Do, While, and Loop are new keywords • The Do While statement marks the beginning of the loop • The Loop statement marks the end • The statements to repeat are found between these and called the body of the loop Do While expression statement(s) Loop
Do While Example Private Sub btnRunDemo_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnRunDemo.Click ' Demonstrate the Do While loop Dim intCount As Integer = 0 Do While intCount < 10 lstOutput.Items.Add("Hello") intCount += 1 Loop End Sub Note that programming styledictates the body of theloop be indented for clarity
Infinite Loops • A loop must have some way to end itself • Something within the body of the loop must eventually force the test expression to false • In the previous example • The loop continues to repeat • intCount increases by one for each repetition • Finally intCount is not <10 and the loop ends • If the test expression can never be false, the loop will continue to repeat forever • This is called an infinite loop
Counters • Variables called counters are frequently used to control Do While loops • See intCount from the previous example • Counters are typically initialized before the loop begins Dim intCount As Integer = 0 • The counter is then modified in the body of the loop intCount += 1 • The test expression ends the loop when the counter compares to some value
Pretest vs. Posttest Loops • Previous Do While loops are in pretest form • Expression is tested before the body of the loop is executed • The body may not be executed at all • Do While loops also have a posttest form • The body of the loop is executed first • Then the expression is evaluated • Body repeats as long as expression is true • The body of a posttest loop must be executed at least once
Posttest Loop Syntax and Flowchart • The statement(s) mustbe executed at leastonce, irrespective of the expression used Do statement(s) Loop While expression statement(s) Expression True False
A Posttest Running Total Loop • Tutorial 5-4 uses the code above in pretest form as part of a more complete example • Tutorial 5-5 demonstrates how to structure a loop such that the user can specify the iterations intCount = 1 ' Initialize the counter decTotal = 0 ' Initialize total Do strInput = InputBox("Enter the sales for day " & _ intCount.ToString, "Sales Amount Needed") If strInput <> "" Then decSales = CDec(strInput) decTotal += decSales ' Add sales to total intCount += 1 ' Increment the counter End If Loop While intCount <= 5
Section 5.4The Do Until andFor Next Loops A Do Until Loop Iterates Until Its Test Expression Is True The For...Next Loop Is Designed to Use a Counter Variable and Iterates a Specific Number of Times
Do Until vs. Do While • A Do While loop • Repeats as long as its test expression is true • Ends when its test expression becomes false • A Do Until loop • Repeats as long as its test expression is false • Ends when its test expression becomes true • The Do Until loop has a pretest and posttest form just as a Do While loop
Do Until: Pretest & Posttest Forms • Pretest: • Posttest: • Tutorial 5-6 provides a hands-on example of a pretest Do Until loop Do Until expression statement(s) Loop Do statement(s) Loop Until expression
Do Until Loop – Test Score Average strInput = InputBox("How many test scores do you " _ & “want to average?", "Enter a Value") intNumScores = CInt(strInput) ‘ Store the starting values in total and count sngTotal = 0 intCount = 1 ‘ Get the test scores Do Until intCount > intNumScores strInput = InputBox("Enter the value for test score " _ & intCount.ToString, "Test Score Needed") sngTotal = sngTotal + CSng(strInput) intCount = intCount + 1 Loop ‘ Calculate the average If intNumScores > 0 then sngAverage = sngTotal / intNumScores Else sngAverage = 0.0 End If
For…Next Loop • Ideal for loops that require a counter • For, To, and Next are keywords • CounterVariable tracks number of iterations • StartValue is initial value of counter • EndValue is counter number of final iteration • Optional Step allows a counter increment other than 1 for each iteration of the loop For CounterVariable = StartValue To EndValue [Step] statement Next [CounterVariable]
For…Next Flowchart set counter to StartValue Counter = EndValue? statement(s) increment counter False True
For…Next Example • The following code from Tutorial 5-7 uses a For…Next loop to place the squares of the numbers 1 through 10 in a ListBox • Tutorial 5-8 uses a For…Next loop to move a PictureBox control around a window For intCount = 1 To 10 intSquare = CInt(intCount ^ 2) strTemp = "The square of " & intCount.ToString _ & “ is “ & intSquare.ToString lstOutput.Items.Add(strTemp) Next intCount
More on the StepValue • It’s optional and if not specified, defaults to 1 • The following loop iterates 11 times with counter values 0, 10, 20, …, 80, 90, 100 • StepValue may be negative, causing the loop to count downward For x = 0 To 100 Step 10 MessageBox.Show("x is now " & x.ToString) Next x For x = 10 To 1 Step -1 MessageBox.Show("x is now " & x.ToString) Next x
Exiting a Loop Prematurely • In some cases it is convenient to end a loop before the test condition would end it • The following statements accomplish this • Exit Do (used in Do While or Until loops) • Exit For (used in For Next loops) • Use this capability with caution • It bypasses normal loop termination • Makes code more difficult to debug
Example: Exit a Loop Prematurely maxNumbers = CInt(InputBox("How many numbers do " & _ "you wish to sum?")) total = 0 For x = 1 to maxNumbers input = InputBox("Enter a number.") If input = "" Then Exit For Else num = CDbl(input) total += num End If Next x MessageBox.Show(“Sum of the numbers is " & total.ToString)
When to Use the Do While Loop • Use Do While when the loop should repeat as long as the test expression is true • Can be written as a pretest or posttest loop • A pretest Do While is ideal when the body should not be perfomed for a test expression that is initially false • Posttest loops are ideal when you always want the loop to iterate at least once
When to Use the Do Until Loop • Use Do Until when the loop should repeat as long as the test expression is false • Can be written as a pretest or posttest loop • A pretest Do Until is ideal when the body should not be perfomed for a test expression that is initially true • Posttest loops are ideal when you always want the loop to iterate at least once
When to Use the For Next Loop • The For...Next loop is a pretest loop ideal when a counter is needed • It automatically increments the counter variable at the end of each iteration • The loop repeats as long as the counter variable is not greater than an end value • Used primarily when the number of required iterations is known
5.6Nested Loops Nested Loops Are Necessary When a Task Performs a Repetitive Operation and That Task Itself Must Be Repeated
Nested Loops • The body of a loop can contain any type of VB statements including another loop • When a loop is found within the body of another loop, it’s called a nested loop
Nested Loop Example • A clock is an example of a nested loop For hours = 0 To 24 lblHours.Text = hours.ToString For minutes = 0 To 59 lblMinutes.Text = minutes.ToString For seconds = 0 To 59 lblSeconds.Text = seconds.ToString Next seconds Next minutes Next hours
Nested Loop Example Analysis • The innermost loop will iterate 60 times for each iteration of the middle loop • The middle loop will iterate 60 times for each iteration of the outermost loop • 24 iterations of the outermost loop requires: • 1,440 iterations of the middle loop • 86,400 iterations of the innermost loop • An inner loop goes through all its iterations for each iteration of the outer loop • Multiply iterations of all loops to get the total iterations of the innermost loop
Section 5.6Multicolumn List Boxes,Checked List Boxesand Combo Boxes A Multicolumn List Box Displays Items in ColumnsA Checked List Box Displays a Check Box Next to Each Item in the List A Combo Box Is Like a List Box Combined With a Text Box
List Box Multicolumn Property • The ListBox has a Multicolumn property • Boolean property with default value of false • If set to true, entries can appear side by side • Below, ColumnWidth is set to 30 • Note the appearance of a horizontal scroll bar in this case
Checked List Box • A form of ListBox with the list box properties and methods already discussed • One item at a time may be selected but many items in a Checked List Box can be checked • The CheckOnClick property determines how items may be checked • False - the user clicks an item once to select it, again to check it • True - the user clicks an item only once to both select it and check it
Finding the Status of Checked Items • The GetItemChecked method returns true if the item at Index has been checked CheckedListBox.GetItemChecked(Index) Dim i as Integer Dim intCheckedCities as Integer = 0 For i = 0 to clbCities.Items.Count – 1 If clbCities.GetItemChecked(i) = True Then intCheckedCities += 1 End If Next i MessageBox.Show(“You checked “ & _ intCheckedCities.Tostring() & “ cities.”)