1 / 46

Chapter 5 Lists, Loops, Validation and More Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI 3131.01

Chapter 5 Lists, Loops, Validation and More Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI 3131.01 . Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine. Topics InputBox ListBox Do…While loop

salena
Download Presentation

Chapter 5 Lists, Loops, Validation and More Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI 3131.01

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 5 Lists, Loops, Validation and More Instructor: Bindra Shrestha University of Houston – Clear Lake CSCI 3131.01

  2. Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine

  3. Topics • InputBox • ListBox • Do…While loop • Do Until and For…Next Loop • Nested Loops • Multicolumn Listbox • Checked List Box • Combo Box • Input Validation • ToolTips

  4. Format of the InputBox Function InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos]) • 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

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

  6. The ListBox Control • A ListBox control displays a list of items and allows the user to select one or more • Drag from Toolbox to create this control on a form

  7. ListBox Items Property • The Items property holds an entire list of values from which the user may choose • The list of values may be established at run time or as part of the form design • ListBox Items.Count Property returns an integer with the number of entries stored in the Items property • Example: • If lstEmployees.Items.Count = 0 Then • MessageBox.Show("The list has no items!") • End If

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

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

  10. ListBoxSelectIndex Property • The SelectIndex property returns an integer with the index of the 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

  11. ListBoxSelectedItem Property • Instead of using the SelectedIndex property as follows: • The SelectedItem property can be used to retrieve the value of a selected item as follows: If lstMonths.SelectedIndex <> -1 Then month = lstMonths.Items(lstMonths.SelectedIndex) End If If lstMonths.SelectedIndex <> -1 Then month = lstMonths.SelectedItem.ToString) End If

  12. ListBox Sorted Property • Sorted is a boolean property • When set to true, values in the Items property are displayed in alphabetical order • When set to false, values in the Items property are displayed in the order they were added • Sorted property can be set in design view and in code • Example in code: • lstFruit.Sorted = True

  13. ListBoxItems.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) • ListBoxis the name of the control • Item is a string value to add to the Items property • Example: lstStudents.Items.Add("Sharon")

  14. ListBoxItems.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")

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

  16. 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")

  17. The Repetition Structure (Loops) Beside the sequence structure and selection structure, programs almost always use repetition structure. The repetition structure is also referred to as a loop structure. With a repetition structure, instructions in the program can be repeatedly executed under certain condition.

  18. Preteset Loop vs. Posttest Loop A pretest loop tests the condition before the instructions in the loop. A posttest loop tests the condition after the instructions in the loop.

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

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

  21. A Posttest Running Total Loop 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 • 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

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

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

  24. Do Until Loop – Test Score Average strInput = InputBox("How many test scores do you " _ & "want to average?", "Enter a Value") intNumScores = CInt(strInput) ' Store starting values 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

  25. The For...Next Statement (For-loop) Use the For...Next statement to code a loop if the precise number of iterations are known. Syntax For counter [As datatype] = startvalue To endvalue [Step stepvalue] Next [counter] Notes: (1) The counter variable declared after For is out of scope after the loop statement exits. (2) The counter variable may also be declared before the loop. (3) The counter variable after the Next keyword may be omitted. (4) The stepvalue may be positive or negative.

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

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

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

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

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

  31. Nested Loop Example • A clock is an example of a nested loop • Minute hand repeats 60 times for each hour • Second hand repeats 60 times for each minute 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

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

  33. 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 - user clicks item once to select it, again to check it • True - user clicks item only once to both select it and check it

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

  35. Combo Boxes Similar to List Boxes • Both display a list of items to the user • Both have Items, Items.Count, SelectedIndex, SelectedItem, and Sorted properties • Both have Items.Add, Items.Clear, Items.Remove, and Items.RemoveAt methods • These properties and methods work the same with combo boxes and list boxes

  36. Combo Box Styles • Simple Combo Box • List is always shown • Drop-down Combo Box • List appears when user clicks down arrow • User can type text or select

  37. Combo Box Styles • Drop-down List Combo Box • Behaves like a Drop-DownCombo Box, but the usermay not enter text directly • Tutorial 5-9 demonstrates each style of combo box

  38. Choosing a Combo Box Style • If restricting the user to select items listed • If empty space – use ListBox • If limited space – use drop-down list ComboBox • If allowing user to select an item listed or enter an entirely new item • If empty space – use simple ComboBox • If limited space – use drop-down ComboBox

  39. Examples of Input Validation • Numbers are checked to ensure they are within a range of possible values • For example, there are 168 hours in a week • A person can’t work more than 168 hours a week • Values are checked for their “reasonableness” • A person might possibly work 168 hours in a week • However, this is highly improbable • Items selected from a menu or a set of choices are checked to ensure these options are available • Variables are checked for values that might cause problems, such as division by zero

  40. CausesValidation/Validating Event • A control’s Validating event is triggered when focus is shifting from that control to a control whose CausesValidation property is true • The Validating event of the control losing the focus fires before focus is lost • This allows your code to validate an entry just before focus shifts • If user shifts focus, input must be complete • Tutorial 5-10 demonstrates this capability

  41. The Validated Event • A control’s Validated event is triggered • After the Validating event • After focus has been lost • Allows operations on input that should occur only after the user moves away from the field

  42. Select Text with SelectAll Method • SelectAll makes correcting invalid input easier • If you know which TextBox is in error you can: • Use the Focus method to position the cursor • Use the SelectAll method to select the text • Then the user need not erase incorrect text • Simply start typing to enter the corrected text • If txtName is in error: txtName.Focus() txtName.SelectAll()

  43. Using the With…End Statement • A With statement establishes a default object in effect until an End With is encountered • Instead of repeating txtNum1 in this code • With allows you to reference the txtNum1 object without specifying it repeatedly txtNum1.SelectionStart = 0 txtNum1.SelectionLength = txtNum1.Text.Length With txtNum1 .SelectionStart = 0 .SelectionLength = .Text.Length End With

  44. What is a Tool Tip? • A Tool Tip is the short text message you see when holding the mouse over a control • These are easy to set up and use in Visual Basic forms • The ToolTip control allows you to create ToolTips for other controls on a form

  45. Setting Up ToolTips • Display the form design window • Double-click the ToolTip tool in the Toolbox • The ToolTip control is invisible at runtime so • It appears in the component tray, not the form • Component tray shows at the bottom of the design window • ToolTips are now enabled for this form • Form controls now have a ToolTip property • This new property holds the text string that will be displayed for that control

  46. Controlling the Tool Tips • Select the ToolTip control from the tray • View Properties window to see the following • An InitialDelay property that regulates the delay before a tip appears • An AutoPopDelay that determines how long a tip is displayed • ReshowDelay determines the time between the display of different tips as the user moves the mouse from control to control

More Related