Top Banner
Chapter 14 • Shipping time application using dates and timers • Create and manipulate Date variables. • Execute code at regular intervals using a Timer control. • Retrieve Date input with a DateTimePicker control. • Group controls using a GroupBox control.
51

Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Dec 20, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14

• Shipping time application using dates and timers

• Create and manipulate Date variables.

• Execute code at regular intervals using a Timer control.

• Retrieve Date input with a DateTimePicker control.

• Group controls using a GroupBox control.

Page 2: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14A seafood distributor has asked you to create an application that will calculate the delivery time for seafood shipped from Portland, Maine, to its distribution center in Las Vegas, Nevada. The distributor has arrangements with local airlines to guarantee that seafood will ship on flights that leave either at noon or at midnight. The airport requires the distributor to drop off the seafood at the airport at least one hour before each flight. When the distributor specifies the drop-off time, the application should display the delivery time in Las Vegas. This application should take into account the three-hour time difference (it’s three hours earlier in Las Vegas) and the six-hour flight time between the two cities. The application should allow the user to select drop-off times within the current day (seafood must be shipped within a day to guarantee freshness). The application should also include a running clock that displays the current time.

Page 3: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14• So basically:

– If the shipment is dropped between 11:00AM and 10:59PM, it is shipped at 12:00AM the next day and reaches Las Vegas at 3:00AM the next day

– If the shipment is dropped between 11:00PM and 10:59AM, it is shipped at 12:00PM the same day and reaches Las Vegas at 3:00PM the same day

• To develop this application we use primitive data type Date.

• Date is the visual basic keyword that corresponds to the DateTime structure in Framework Class Library (FLC)

Page 4: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14• Dim delivery As Date = New Date (2003, 1,1, 0, 0, 0)• Keyword NEW calls the Date structures constructor• A constructor is a procedure that initializes a class

object or structure value when it is created.

Argument Range Description

Initializing a Date variable using New Date (year, month, day, hour, minute, second)

year Integer values 1–9999 Specifies the year.

month Integer values 1–12 Specifies the month of the year.

day Integer values 1–number of days in month

Specifies the day of the month. Each month has 28 to 31 days depending on the month and year.

hour Integer values 0–23 Specifies the hour of the day. The value 0 represents 12:00 A.M.

minute Integer values 0–59 Specifies the minute of the hour.

second Integer values 0–59 Specifies the number of elapsed seconds in the current minute.

YYYY, MM, DD, H, M, S

Page 5: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14•Using Date Members:

– You can access the properties of your new date variable by using the “dot” (.) operator e.g.

•Now to manipulate the date variable “delivery” we call methods associated with the variable.•To assign the current date and time

– Dim currentTime AS Date=Date.Now

year=delivery.Yearmonth=delivery.Monthday=delivery.Dayhour=delivery.Hourminute=delivery.Minutesecond=delivery.Second

Delivery=delivery.AddHours(3)(Adds 3 hours)

Delivery=delivery.AddMinutes(-5)Subtract 5

minutes

Page 6: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14

• To assign current date, you don’t need “new date()” because the date.now property returns a date value

• GroupBox Control: Visually groups related controls by drawing a labeled box around them

• DateTimePicker control allows users to enter date and time information.

Page 7: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14 - Pseudocode• When the form loads:

Set range of possible drop-off times to any time in the current dayDetermine the shipments delivery timeDisplay the shipment’s delivery time

• When the user changes the drop-off time:Determine the shipments delivery timeDisplay the shipments delivery time

• After one second has elapsed:Update the current time displayed

• When the displaydeliverytime procedure gets called:Determine the time the shipment flight departsAdd three hours to determine the delivery time (time zone + flight time)Display the delivery time

• When the DepartureTime procedure gets called:Select correct case based on the hour the shipment was dropped offCase where drop-off hours is between the value 0 and 10

Delivery set to depart on noon flight of current dayCase where the drop off hour is 23

Delivery set to depart on noon flight of next dayCase where none of the preceding cases match

Delivery set to depart on midnight flight of current day

Page 8: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14• Insert the group box• Insert the label and name it appropriately• Insert the DateTimePicker. Change

Format from Long to Custom and then change the custom format to hh:mm tt

• Select the dateTimePicker ShowUpDown property to true.

• Add a timer control. A timer control generates a tick at regular intervals that further executes an event handler

Page 9: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14

• Set the timer control to 1000 mS. Try with 10,000 to notice the difference. Set enabled to true and rename to clockTimer

• Now unlike previous applications, event for this application occurs during the form load

• Store the current date and time in the date variable currentTime– Dim currentTime as Date = Date.Now

Page 10: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14• Set the drop off hours. You want to set minimum

and maximum for dropoff times.• dropOffDateTimePicker.MinDate = New Date

(currentTime.Year, currentTime.Month, currentTime.Day, 0, 0, 0)

• dropOffDateTimePicker.MaxDate=dropOffDateTimePicker.MinDate.AddDays(1)

• Also in the form load event handler, call the procedure which displays the DeliveryTime– DisplayDeliveryTime(). This is a sub procedure instead

of a function because we do not expect it to return a value.

Page 11: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14•The same procedure DisplayDeliveryTime() is also called when the dropOffDateTimePicker’s value changes

•So double click the picker and call the subprocedure DisplayDeliveryTime()

•Now define the DisplayDeliveryTime procedure.

Page 12: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14

• Sub DisplayDeliveryTime()‘Print initial delivery time

Dim delivery As Date = DepartureTime()

‘Add 3 hours to departure time and display results

Delivery=delivery.AddHours(3)

lasVegasTimeLabel.Text = delivery.ToLongDateString & “ at” & delivery.ToShortTimeString

End Sub

Page 13: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 14

• Now to calculate the DepartureTime()

• Now since DepartureTime is returning a value, it will be programmed as a function

• Function DepartureTime() As DateDim currentDate As Date = Date.Now

Dim departTime As Date

‘Determine which flight the shipment takes

Page 14: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Sub DisplayDeliveryTime()

'Print initial delivery time Dim delivery As Date = DepartureTime()

'Add 3 hours to departure time and display results delivery = delivery.AddHours(3) lasVegasTimeLabel.Text = delivery.ToLongDateString & " at" & delivery.ToShortTimeString End Sub

Function departuretime() As Date Dim currentdate As Date = Date.Now Dim departtime As Date

Select Case dropOffDateTimePicker.Value.Hour

Case 0 To 10 departtime = New Date(currentdate.Year, currentdate.Month, currentdate.Day, 12, 0, 0) Case 23 currentdate = currentdate.AddDays(1) departtime = New Date(currentdate.Year, currentdate.Month, currentdate.Day, 12, 0, 0) Case Else currentdate = currentdate.AddDays(1) departtime = New Date(currentdate.Year, currentdate.Month, currentdate.Day, 0, 0, 0)

End Select Return departtime

End Function

Page 15: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Add timer event

• Double click the timer– currentTimeLabel.Text =

String.Format("{0:hh:mm:ss tt}", Date.Now)

Page 16: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 15

• Create variables that can be used throughout the form

• Pass argument by reference i.e. Use ByRef (instead of ByVal)

• Remove data type errors by using option strict

• Change a value from one data type to another using methods in class convert.

Page 17: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Problem

• An organization is collecting donations. A portion of each donation is used to cover the operating expenses of the organization; the rest of the donation goes to the charity. Create an application that allows the organization to keep track of the total amount of money raised. The application should deduct 17% of each donation for operating costs; the remaining 83% is given to the charity. The application should display the amount of each donation after the 17% operating expenses are deducted; it also should display the total amount raised for the charity (that is, the total amount donated less all operating costs) for all donations up to that point.

Page 18: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Problem

• If we follow the methodology we have learned so far, the solution is simple. Create a button click event and add the following code:

donatedValueLabel.Text = CalculateDonation(Val(donationTextBox.Text))

totalValueLabel.Text += Val(donatedValueLabel.Text)

• But lets do it differently so that we can learn pass by reference.

Page 19: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Key points

• We need a variable which can store the running value of donations. So we declare an instance variable – a variable that is declared inside a class but outside of all procedure definitions of that class.

• All procedures in the class FundRaiserForm will have access to this variable and will be able to modify its value.

Page 20: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Example of variable types

Public class FundRaiserForm

Dim totalRaised As Decimal ‘Module Scope

Private Sub calculateTotal (ByVal amount As Decimal)

Dim expenses as Decimal ‘Procedure Scope

For expenses =1 to 10 step 5

Dim totalExpenses as Decimal ‘Block Scope

Next

End Class

• totalRaised can be accessed by anyone in the class

• expenses can only be accessed from within calculateTotal

• totalExpenses can only be accessed within the For-Next Statement

Page 21: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Scope of variables

• Module scope – Variables valid for the entire module of class.

• Procedure scope – Variables valid inside the procedure and cannot be accessed from outside.

• Block Scope – Variables valid inside the block and ends at the end of the block

• The Procedure & Block scope variables are called local variables.

Page 22: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 15 Application

• So After Public Class initialize the variableDim totalRaised As Decimal = 0 ‘Module Variable

• Create calculateDonation functionFunction CalculateDonation(ByVal donatedAmount As

Decimal) As DecimalConst COSTS As Double = 0.17Dim netDonation AS DecimalnetDonation= convert.ToDecimal(donatedAmount – (donatedAmount*Cost)Return netDonation

End Function

Page 23: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

App development (Cont.)

• Now Create the button click event handler– Create local variables for the button

Dim donation as Decimal ‘ amount donated ‘Procedure Variable

Dim afterCosts As Decimal ‘amount for charity

Donation = val (donationTextBox.Text)

afterCosts = CalculateDonation(donation)donatedValueLabel.Text = String.Format(“{0:c}”, afterCosts)

totalRaised +=afterCosts

totalValueLabel.Text=String.Format (“{0:c}”,totalRaised)

Page 24: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Pass-by-Value vs. Pass-by-Reference

• Pass-by-value (KeyWord ByVal): Indicates that a variable has been passed by value. Application makes a copy of the variable and changes made to this variable does not affect the original variable.

• Pass-by-reference (ByRef): Indicated that address of memory location of original variable is passed and the called procedure can modify the value of the original variable.

Page 25: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Pass-by-Reference

• ReplaceafterCosts = CalculateDonation(donation)

byCalculateDonation(donation, afterCosts)

• Donation will be passed ByVal and afterCosts will be passed ByRef

• Replace the function CalculateDonation by following sub procedureSub CalculateDonation (ByVal donatedAmount As

Decimal, ByRef netDonation As Decimal)Const Costs As Double = 0.17netDonation=donatedAmount – (donatedAmount*Cost)End Sub

Page 26: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Explanation

• Since netDonation is a pointer to the actual memory location where afterCosts is stored, any changes to netDonation is written on to afterCosts.

• This is tricky and can produce logical errors. Thus it is only used by experienced programmers.

Page 27: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Option Strict

• If I say something costs 50, how will you interpret it? Dollars, yen, euros, pesos, rupees). It makes a difference, right!!!

• If it’s a different currency, you will have to convert it in the currency you have.

• VB does some conversions e.g. integer to decimal without coding. This is implicit conversion.

Page 28: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Data Type Conversions

Data Type Can be implicitly converted to these (larger) types

Boolean Object

Byte Short, Integer, Long, Decimal, Single, Double or Object

Char String or Object

Date Object

Decimal Single, Double or Object

Double Object

Integer Long, Decimal, Single, Double or Object

Long Decimal, Single, Double or Object

Object none

Short Integer, Long, Decimal, Single, Double or Object

Single Double or Object

String Object

LARGER- means can store more data than the type in the left e.g. integer can store values in the range of ± 2.1billion and a long can store in the range of ± 9x1018

This type of conversion is called implicit widening conversion and no data loss happens

Page 29: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Data Type Conversion

• However if we do the reverse, i.e. assign larger type to smaller type, it will create an error

Dim value1 as Double=4.6Dim value2 as Integer = value1

• This will result in 5 being assigned to value2. This is called implicit narrowing conversions

• VB provides a feature called, “Option Strict” which generates a syntax error incase of implicit narrowing conversions.

• Right click project in solutions explorer. Then under compile window set it to on. Or add ‘option strict off’ before the form class.

Page 30: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Option Strict

• Now since implicit conversion is not happening, there are explicit ways to convert data.

• These can be accessed by ‘convert.’

Convert To Use Convert Method Sample Statement

Integer ToInt32 value = Convert.ToInt32( _ Val(inputTextBox.Text))

Decimal ToDecimal value = Convert.ToDecimal( _ Pmt(monthlyInterest, _ months,-loanAmount))

Double ToDouble rate = Convert.ToDouble( _ Val(rateTextBox.Text)) / 100

String ToString result = Convert.ToString(total)

Page 31: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

1 Public Class FundRaiserForm

2 ' instance variable stores total raised for charity

3 Dim totalRaised As Decimal = 0

4

5 ' returns donation amount after operating expenses

6 Sub CalculateDonation(ByVal donatedAmount As Decimal, _

7 ByRef netDonation As Decimal)

8

9 Const COSTS As Double = 0.17

10

11 ' calculate amount of donation for charity

12 netDonation = Convert.ToDecimal(donatedAmount - _

13 (donatedAmount * COSTS))

14 End Sub ' CalculateDonation

15

16 ' handles Donation: TextBox’s TextChanged event

17 Private Sub donationTextBox_TextChanged(ByVal sender As _

18 System.Object, ByVal e As System.EventArgs) _

19 Handles donationTextBox.TextChanged

20

21 donatedValueLabel.Text = "" ' clear After expenses: field

22 End Sub ' donationTextBox_TextChanged

23

Outline

• (1 of 2 )

Procedure CalculateDonation determines the amount of donation after operating costs; parameter netDonation is modified directly (using ByRef)

Instance variable declaration

Converting the calculation resultto type Decimal

Page 32: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

24 ' handles Make Donation Button’s Click event

25 Private Sub donateButton_Click(ByVal sender As System.Object, _

26 ByVal e As System.EventArgs) Handles donateButton.Click

27

28 Dim donation As Decimal ' amount donated

29 Dim afterCosts As Decimal ' amount for charity

30

31 ' get donation amount

32 donation = Convert.ToDecimal(Val(donationTextBox.Text))

33

34 ' obtain donation amount after operating costs deduction

35 CalculateDonation(donation, afterCosts)

36

37 ' display amount of donation after costs

38 donatedValueLabel.Text = String.Format("{0:C}", afterCosts)

39

40 ' update total amount of donations received

41 totalRaised += afterCosts

42

43 ' display total amount collected for charity

44 totalValueLabel.Text = String.Format("{0:C}", totalRaised)

45 End Sub ' donateButton_Click

46 End Class ' FundRaiserForm

Outline

• (2 of 2 )

Convert donation amount from a String to a Decimal value

afterCosts is passed by reference

Page 33: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Chapter 17

• Create and initialize arrays

• Store information in arrays

• Refer to individual elements of an array

• Sort arrays

• Use ComboBoxes to display options

• Convert a string to lowercase characters

• Insert characters in a String

Page 34: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Arrays• Are data structures that group data items of

similar type e.g. DaysOfWeek(0 to 6)

Monday Tuesday Wednesday Thursday Friday Saturday Sunday

0 1 2 3 4 5 6

•DaysofWeek(0)= Monday

•DaysofWeek(1)=Tuesday

: :

: :

•DaysofWeek(6)=Sunday

SEVEN ELEMENTS

First Element Seventh Element

Position 0 Position6 (n-1)

Position numbers

Name of Array Elements

Page 35: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Arrays• The position number inside the array is

called an index or subscript e.g. daysOfWeek(5)

• Index can be 0, positive integer, or an integer expression (e.g. value1+value2)

• So if value1=2 and value2=4 then daysOfWeek(value1+value2)=Sunday

• So A(12) will have 13 elements starting from A(0) to A(12)

• You can perform operations on the array elements e.g. Y=A(0)+A(1)

Index

Page 36: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Arrays

• Arrays need to be declared and initializedDim netUnitsSold As Integer( )

netUnitsSold = New Integer(0 To 12) { }

This tells that its an array

Keyword: Allocates memory

Array Bounds (n-1)

Initializer List: If empty then array initialized by default values e.g. 0 for numeric, false for boolean, and nothing for references

Page 37: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Other ways to declare an array

• Dim salesPerDay As Integer()

• SalesPerDay = New Integer(){2,4,6,8}– Notice array of size 4 (0-3) is automatically

created based on number of elements

• Dim temperature As Double() = New Double(0 to 3) { 23, 24, 25, 45}

Page 38: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Application Total of array• Dim array As Integer()• array = New Integer(9) {} 'array = New Integer(0 To 9) {}• Dim populate As Integer = 0• For populate = 0 To array.GetUpperBound(0) Step 1• array(populate) = populate + 1• Next

• 'Dim array As Integer() = New Integer() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}• Dim total As Integer = 0• Dim index As Integer = 0

• 'For index = 0 To 9 Step 1• 'total += array(index)• 'Next

• 'For index = 0 To (array.Length - 1) Step 1• 'total += array(index)• 'Next

• For index = array.GetLowerBound(0) To array.GetUpperBound(0) Step 1• ' array.GetUpperBound(0) 0 because it suggests a one dimensional array.• total += array(index)• Next

• 'resultLabel.Text = total• resultLabel.Text = Convert.ToString(total)

Page 39: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Flag Quiz Application

A geography teacher would like to quiz students on their knowledge of the flags of various countries. The teacher has asked you to write an application that displays a flag and allows the student to select the corresponding country from a list. The application should inform the user of whether the answer is correct and display the next flag. The application should display five flags randomly chosen from the flags of Australia, Brazil, China, Italy, Russia, South Africa, Spain and the United States. When the application is run, a given flag should be displayed only once.

Page 40: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Pseudocode• On form load

– Sort the country names alphabetically

– Place names in the combo box– Select flags randomly– Display the flag

• When user clicks the Submit Button:– Retrieve country name from

combo box– If selected value matches correct

value • Display correct

– Else Display incorrect– If five images have been

displayed• Append Done to the label text• Disapble buttons and combo box

– Else Disable submit button– Enable Next button

• When user clicks the next button– Randomly choose the next flag

that has not been previously displayed

– Display the flag– Clear the labels text– Set combobox to display its first

item– Update the number of flags

shown– Enable submit button– Disable next flag button

Page 41: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

App development

• Step 1 Create an array below class declaration'String Array to store countries Dim options As String() = New String() {"Russia",

"China", "United States", "Italy", "Australia", "South Africa", "Spain", "Brazil"}

'Boolean array to track displayed flags Dim used As Boolean() = New Boolean(0 To

options.GetUpperBound(0)) {}• GetUpperBound returns the index of the last

element in the array (7 in this case) so that “used” array can mirror “options” array

• Options.length will return 8

Page 42: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

App development

• Initialize the counter variablesDim count As Integer = 1 'number of flags shown

Dim country As String 'current flag's country

• Add comboBox to the form (combines textBox and listbox)– Rename it to optionsComboBox– Set MaxDropDownItems=4

• ComboBox should be populated when the form loads… so create a form load event

Page 43: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Removing White Spaces• At form load

– optionsComboBox.DataSource = options

• Create function procedure to build the flag-image file’s path name

• The flags are located in the \FlagQuiz\bin\Debug\images folder … Now add these lines

Function BuildPathName() As String

Dim output As String = country

Dim space As Integer = output.IndexOf(" ")

If space > 0 Then

output = output.Remove(space, 1)

End If

Page 44: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Removing White Spaces

• Remove white spaces: Countries like South Africa and United States have space between names which need to be removed to match the file name

• String method IndexOf(“ “) assigns to space the index where space (“ “) character exists e.g. IndexOf(“S”) for united states will return 7 (U is 0 and S is 7

• If no space exists, then indexOff returns -1

• If space if found then remove method removes the space

• So now United States becomes UnitedStates

Page 45: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Ensuring all characters are lower case

output = output.ToLower() ‘Converts string to lower case

output &= ".png“ ‘ Appends .png to country name

output = output.Insert(0, System.Environment.CurrentDirectory & "\images\") ‘At location 0 of the string insert path

Return output

Page 46: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Ensure that same random flag does not get displayed twice

• Create another function:Function GetUniqueRandomNumber() As Integer Dim randomObject As Random = New Random Dim randomNumber As Integer Do randomNumber = randomObject.Next(0, used.Length) ‘

Generates random numbers between two numbers Loop Until used(randomNumber) = False used(randomNumber) = True ‘ Mark index as used Return randomNumber End Function

• So this functions returns an unused random number from a pool of numbers described by indices of the “used” array.

Page 47: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Display Flag

• Now you have full path of the flag• You also have a random number for the flag.• Now get the country details using the random

number and from the country details get the flag imageSub displayFlag() Dim randomNumber As Integer =

GetUniqueRandomNumber() country = options(randomNumber) Dim path As String = BuildPathName() flagPicture.Image = Image.FromFile(path) End Sub

Page 48: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Displaying first flag

• In the form load, after populating the combo box, call the sub procedure

displayFlag( )

• Now create the event handler for the submit button– You know the name of the flag (user input)

and you know the country (Stored in country) so this should be easy

Page 49: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Event Handler• Private Sub submitButton_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles submitButton.Click Dim response As String = Convert.ToString(optionsComboBox.SelectedValue) If response = country Then feedbackLabel.Text = "Correct!" Else feedbackLabel.Text = "Sorry, incorrect!" End If If count >= 5 Then feedbackLabel.Text &= " Done" nextButton.Enabled = False submitButton.Enabled = False optionsComboBox.Enabled = False Else submitButton.Enabled = False nextButton.Enabled = True End If End Sub

Page 50: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Adding the next button event

displayFlag()

feedbackLabel.Text = ""

optionsComboBox.SelectedIndex = 0

count += 1

submitButton.Enabled = True

nextButton.Enabled = False

Page 51: Chapter 14 Shipping time application using dates and timers Create and manipulate Date variables. Execute code at regular intervals using a Timer control.

Sorting Arrays

• If the country names were sorted, the users can find the names much faster.

• Immediately after form loads add array.sort(options)

• Try adding this line after optionsComboBox.DataSource=options and see the difference.