Presentation is loading. Please wait.

Presentation is loading. Please wait.

Starting Out with Visual Basic.NET 2 nd Edition Chapter 5 Lists, Loops, Validation, and More.

Similar presentations


Presentation on theme: "Starting Out with Visual Basic.NET 2 nd Edition Chapter 5 Lists, Loops, Validation, and More."— Presentation transcript:

1 Starting Out with Visual Basic.NET 2 nd Edition Chapter 5 Lists, Loops, Validation, and More

2 Starting Out with Visual Basic.NET 2 nd Edition 5.1 Introduction

3 Starting Out with Visual Basic.NET 2 nd Edition Chapter 5 Topics This chapter covers the Visual Basic.NET looping statements Do … While Do … Until For … Next It also discusses the use of List Boxes Combo Boxes

4 Starting Out with Visual Basic.NET 2 nd Edition 5.2 Input Boxes Input Boxes Provide a Simple Way to Gather Input Without Placing a Text Box on a Form

5 Starting Out with Visual Basic.NET 2 nd Edition Format of the InputBox Function Prompt - message to the user 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 Title and beyond are optional arguments InputBox(Prompt [,Title] [,Default] [,Xpos] [,Ypos])

6 Starting Out with Visual Basic.NET 2 nd Edition Sample InputBox Usage userInput = InputBox("Enter the distance.", "Provide a Value", "150")

7 Starting Out with Visual Basic.NET 2 nd Edition 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/440 inch

8 Starting Out with Visual Basic.NET 2 nd Edition 5.3 List Boxes List Boxes Display a List of Items and Allow the User to Select an Item From the List

9 Starting Out with Visual Basic.NET 2 nd Edition ListBox Items Property This property holds the list of items from which the user may choose The value may be established at design time and/or run time

10 Starting Out with Visual Basic.NET 2 nd Edition ListBox Items.Count Property This property holds the number of items that are stored in the Items property Example of use: If lstEmployees.Items.Count = 0 Then MessageBox.Show("There are no items in the list!") End If

11 Starting Out with Visual Basic.NET 2 nd Edition Item Indexing The Item property values can be accessed under program control 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

12 Starting Out with Visual Basic.NET 2 nd Edition ListBox SelectIndex Property The index of the user selected item is available as the value of the SelectIndex property If the user did not select any item, the value is set to -1 (an invalid index value) Example: If lstLocations.SelectedIndex <> -1 Then location = lstLocations.Items(lstLocations.SelectedIndex) End If

13 Starting Out with Visual Basic.NET 2 nd Edition ListBox SelectedItem Property When an item has been selected, this property, SelectedItem, contains the selected item itself

14 Starting Out with Visual Basic.NET 2 nd Edition ListBox Sorted Property The value of this property, if true, causes the items in the Items property to be displayed in alphabetical order

15 Starting Out with Visual Basic.NET 2 nd Edition ListBox Items.Add Method To add items to the end of a ListBox list at run time, use the Add method ListBox.Items.Add(Item) Example lstStudents.Items.Add("Sharon")

16 Starting Out with Visual Basic.NET 2 nd Edition ListBox Items.Insert Method To add items at a specific position in a ListBox list at run time, use the Insert method ListBox.Items.Insert(Index, Item) Example making the 3rd item "Jean" lstStudents.Items.Insert(2, "Jean")

17 Starting Out with Visual Basic.NET 2 nd Edition ListBox Items.Remove, Items.Clear, and Items.RemoveAt Methods ListBox.Items.Remove(Item) Removes the item named by value ListBox.Items.RemoveAt(Index) Removes the item at the specified index ListBox.Items.Clear() Removes all items in the Items property

18 Starting Out with Visual Basic.NET 2 nd Edition 5.4 The Do While Loop A Loop Is Part of a Program That Repeats

19 Starting Out with Visual Basic.NET 2 nd Edition Repetition Structure (Loop) Visual Basic.NET has three structures for repeating a statement or group of statements Do While Do Until For Next

20 Starting Out with Visual Basic.NET 2 nd Edition Do While Flowchart The Do While loop If/While the expression is true, the statement(s) are executed Expression statement(s) False True

21 Starting Out with Visual Basic.NET 2 nd Edition Do While Syntax "Do", "While", and "Loop" are new keywords The statement, or statements are known as the body of the loop Do While expression statement(s) Loop

22 Starting Out with Visual Basic.NET 2 nd Edition 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 count As Integer = 0 Do While count < 10 lstOutput.Items.Add("Hello") count += 1 Loop End Sub

23 Starting Out with Visual Basic.NET 2 nd Edition Infinite Loops Generally, if the expression is true and, hence the loop starts executing: Something within the body of the loop must eventually make the test expression false Otherwise, the Do While loop will continuously loop forever - called an infinite loop

24 Starting Out with Visual Basic.NET 2 nd Edition Counters Variables called counters are frequently used to control Do While loops (see count in the previous example Counters are invariably initialized before the loop begins (above: Dim count As Integer = 0 ) They are also usually modified within the body of the loop (above: count += 1 )

25 Starting Out with Visual Basic.NET 2 nd Edition Pretest vs. Posttest Loops The preceding Do While loops were written in their pretest syntax The expression is always tested before the body of the loop is executed Do While loops also have a posttest form In these, the body of the loop is always executed first, then the expression is evaluated to check to see if additional iterations are needed

26 Starting Out with Visual Basic.NET 2 nd Edition Posttest Do While Syntax and Flowchart The statement(s) will always be done once, irrespective of the expression used Do statement(s) Loop While expression Expression statement(s) False True

27 Starting Out with Visual Basic.NET 2 nd Edition Example: Keeping a Running Total count = 1' Initialize the counter total = 0' Initialize total Do input = InputBox("Enter the sales for day " & _ count.ToString, "Sales Amount Needed") If input <> "" Then sales = CDec(input) total += sales ' Add sales to total count += 1 ' Increment the counter End If Loop While count <= 5

28 Starting Out with Visual Basic.NET 2 nd Edition 5.5 The Do Until and For Next Loops The Do Until Loop Iterates Until Its Test Expression Is True The For...Next Loop Is Designed to Use a Counter Variable to Iterate a Specific Number of Times

29 Starting Out with Visual Basic.NET 2 nd Edition Do Until: Pretest and Posttest Forms Pretest: Posttest: Do Until expression statement(s) Loop Do statement(s) Loop Until expression

30 Starting Out with Visual Basic.NET 2 nd Edition Pretest Do Until Example input = InputBox("How many test scores do you want " & _ "to average?", "Enter a Value") numScores = Val(input) total = 0 count = 1 Do Until count > numScores input = InputBox("Enter the value for test score " & _ count.ToString, "Test Score Needed") total = total + Val(input) count = count + 1 Loop

31 Starting Out with Visual Basic.NET 2 nd Edition For … Next Loop, I The syntax is Where 'For', 'To', and 'Next' are keywords Other details follow … For CounterVariable = StartValue To EndValue [Step x] statement Next [CounterVariable]

32 Starting Out with Visual Basic.NET 2 nd Edition For … Next Loop, II CounterVariable is a numeric counter variable StartValue is the initial value of the counter EndValue gives the number to test for completion Step indicates the increment for count at the end of each iteration; it is optional and defaults to 1 if not specified

33 Starting Out with Visual Basic.NET 2 nd Edition For…Next Flowchart Counter beyond EndValue? statement(s) False True set counter to StartValue increment counter

34 Starting Out with Visual Basic.NET 2 nd Edition For…Next Example For count = 1 To 10 square = count ^ 2 str = "The square of " & count.ToString & " is " & _ square.ToString lstOutput.Items.Add(str) Next count

35 Starting Out with Visual Basic.NET 2 nd Edition More on the StepValue It is optional, if not specified, it defaults to 1 It may be negative, in which case the loop counts downwards 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

36 Starting Out with Visual Basic.NET 2 nd Edition Exiting a Loop Prematurely In some situations it is convenient to be able to gracefully end a loop early Exit Do (used in Do While or Until loops) Exit For (used in For Next loops) Will accomplish that task Since these override the normal loop termination mechanism, they should be used sparingly

37 Starting Out with Visual Basic.NET 2 nd Edition Exiting a Loop Prematurely, Example 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("The sum of the numbers is " & total.ToString)

38 Starting Out with Visual Basic.NET 2 nd Edition When to Use the Do While Loop Use the Do While loop when you wish the loop to repeat as long as the test expression is true You can write the Do While loop as a pretest or posttest loop Pretest Do While loops are ideal when you do not want the loop to iterate if the test expression is false from the beginning Posttest loops are ideal when you always want the loop to iterate at least once

39 Starting Out with Visual Basic.NET 2 nd Edition When to Use the Do Until Loop Use the Do Until loop when you wish the loop to repeat until the test expression is true You can write the Do Until loop as a pretest or posttest loop Pretest Do Until loops are ideal when you do not want the loop to iterate if the test expression is true from the beginning Posttest loops are ideal when you always want the loop to iterate at least once

40 Starting Out with Visual Basic.NET 2 nd Edition When to Use the For Next Loop The For...Next loop is a pretest loop that first initializes a counter variable to a starting value 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 The For...Next loop is primarily used when the number of required iterations is known

41 Starting Out with Visual Basic.NET 2 nd Edition 5.6 Nested Loops Nested Loops Are Necessary When a Task Performs a Repetitive Operation and That Task Itself Must Be Repeated

42 Starting Out with Visual Basic.NET 2 nd Edition Nested Loop Example, I 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

43 Starting Out with Visual Basic.NET 2 nd Edition Nested Loop Example, II 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 When the outermost loop has iterated 24 times, the middle loop will have iterated 1440 times and the innermost loop will have iterated 86,400 times.

44 Starting Out with Visual Basic.NET 2 nd Edition 5.7 Multicolumn List Boxes, Checked List Boxes and Combo Boxes A Multicolumn List Box Displays Items in Columns With a Horizontal Scroll Bar, If Necessary A 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

45 Starting Out with Visual Basic.NET 2 nd Edition List Box Multicolumn Property When this property is set to true (false is the default), entries can appear side by side Below, ColumnWidth is set to 30

46 Starting Out with Visual Basic.NET 2 nd Edition Checked List Box Items in list boxes can be checked (in addition to being selected) The CheckOnClick property values are 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

47 Starting Out with Visual Basic.NET 2 nd Edition Checking the Status of Checked Items The method CheckedListBox.GetItemChecked(Index) Returns true if the indexed item is checked, otherwise, false

48 Starting Out with Visual Basic.NET 2 nd Edition Combo Boxes Are Much Like List Boxes They both display a list of items to the user They both have Items, Items.Count, SelectedIndex, SelectedItem, and Sorted properties They both have Items.Add, Items.Clear, Items.Remove, and Items.RemoveAt methods All of these properties and methods work the same with combo boxes and list boxes

49 Starting Out with Visual Basic.NET 2 nd Edition Combo Boxes Also Have: An area like a text box The user may enter text into that area Or the user may fill it by selecting text from the choices provided

50 Starting Out with Visual Basic.NET 2 nd Edition Combo Box Styles, I Simple Combo BoxDrop-down Combo Box

51 Starting Out with Visual Basic.NET 2 nd Edition Combo Box Styles, II Drop-down List Combo Box Behaves like a Drop-Down Combo Box, but the user may not enter text directly

52 Starting Out with Visual Basic.NET 2 nd Edition 5.8 Input Validation As Long As the User of an Application Enters Bad Input, the Application Will Produce Bad Output Applications Should Be Written to Filter Out Bad Input

53 Starting Out with Visual Basic.NET 2 nd Edition 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 - It is not possible for a person to work more than 168 hours in one week Values are checked for their “reasonableness” Although it might be possible for a person to work 168 hours in a week, it is not probable Items selected from a menu or other sets of choices are checked to ensure they are available options Variables are checked for values that might cause problems, such as division by zero

54 Starting Out with Visual Basic.NET 2 nd Edition CausesValidation/Validating Event A control’s Validating event is triggered just before the focus is shifted to another control whose CausesValidation property is set to true This allows one's code to validate an entry just before focus shifts (clearly after the user thinks the input is finished)

55 Starting Out with Visual Basic.NET 2 nd Edition Using the With…End Statement This statement establishes a default object Instead of this code Use this code txtNum1.SelectionStart = 0 txtNum1.SelectionLength = txtNum1.Text.Length With txtNum1.SelectionStart = 0.SelectionLength =.Text.Length End With

56 Starting Out with Visual Basic.NET 2 nd Edition 5.9 Tool Tips Tool Tips Are a Standard and Convenient Way of Providing Help to the Users of an Application Visual Basic.NET Provides the ToolTip Control, Which Allows You to Assign Tool Tips to the Other Controls on a Form

57 Starting Out with Visual Basic.NET 2 nd Edition What is a Tool Tip? Those little text messages that you see when you pause the mouse cursor over a control They are available for use on Visual Basic.NET forms

58 Starting Out with Visual Basic.NET 2 nd Edition Where the Tool Tip Text is Placed Add the ToolTip control to your form It is visible in Design View But is invisible at Run Time Now controls have a new property with the name you gave to the above ToolTip control This new property holds the text string that will be displayed for that control

59 Starting Out with Visual Basic.NET 2 nd Edition Controlling the Tool Tips The ToolTip control has an InitialDelay property that regulates the delay before a tip appears It also has a AutoPopDelay determines how long a tip is displayed ReshowDelay determines the minimum time between displaying different tips (as the user moves the mouse about the screen)


Download ppt "Starting Out with Visual Basic.NET 2 nd Edition Chapter 5 Lists, Loops, Validation, and More."

Similar presentations


Ads by Google