The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.

'Coding' or 'Programming' for you probably mean 'software engineering' - i.e. the science of building software applications. Persons new to the field often confuse knowledge of a specific programming language (e.g. Java, C++, PHP, Python) with the skill of software engineering. A programming language is a simply a means of achieving the goal of building an application. This course can help you design and develop these systems via the .Net technologies.

This course aims to introduce students to the basic concepts of Visual Programming. In this course the students will be involved in the development of graphical user interfaces (GUI), designing complete windows applications, creating and using custom controls, developing web database applications, learning some of the new and more advanced programming concepts introduced in Visual Basic (VB) and the .NET framework. The skills that you gain from this course can be applied at daily life and your tomorrow workplace to solve related programming problems or for setting up your own software-based business.

Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by Choo Jun Tan, 2021-01-01 11:31:15

Visual Programming

'Coding' or 'Programming' for you probably mean 'software engineering' - i.e. the science of building software applications. Persons new to the field often confuse knowledge of a specific programming language (e.g. Java, C++, PHP, Python) with the skill of software engineering. A programming language is a simply a means of achieving the goal of building an application. This course can help you design and develop these systems via the .Net technologies.

This course aims to introduce students to the basic concepts of Visual Programming. In this course the students will be involved in the development of graphical user interfaces (GUI), designing complete windows applications, creating and using custom controls, developing web database applications, learning some of the new and more advanced programming concepts introduced in Visual Basic (VB) and the .NET framework. The skills that you gain from this course can be applied at daily life and your tomorrow workplace to solve related programming problems or for setting up your own software-based business.

Keywords: Wawasan Open University

iii. ”C” for marks greater than or equal to 60

iv. ”D” for marks greater than or equal to 50 and

v. ”F” for marks below 50.

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 Sub Main()
2 Console.Write("Please enter your marks: ")
3 Dim marks As Double = Console.ReadLine()

4

5 If marks >= 80 Then
6 Console.WriteLine("A")
7 ElseIf marks >= 70 Then
8 Console.WriteLine("B")
9 ElseIf marks >= 60 Then
10 Console . WriteLine ( " C " )
11 ElseIf marks >= 50 Then
12 Console . WriteLine ( " D " )
13 Else
14 Console . WriteLine ( " F " )
15 End If
16 End Sub

Suppose a mark is greater than or equal to 80, the first four conditions are true. However, only the
Console.WriteLine(”A”) statement is executed because your VB program will test the condition line
by line (from top to bottom) until the condition is met. Note that particular Console.WriteLine (”A”) is

executed, the Else part of the ”outer” If ElseIf structure is skipped.

3. Suppose that you try running the compiled program, by pressing <F5>, it will show the respective

grade according to the entered marks from user.

4. Click on Save All icon to save the work.

5.3.6 Activity

1. Write a program to prompt a user to input two numbers and find the larger of two numbers. Use

If ElseIf structure to answer the following conditions.

i. If the first number is larger than the second number, then display the message ”First
number is larger than second number”.

ii. If the second number is larger than the first number, then display the message ”Second
number is larger than first number”.

iii. If the first number and the second numbers are equal, then display the message ”These
two numbers are equal”.

101

2. Determine the output of the following code.

i. Welcome program

1 Sub Main()
2 Console.Write("Please enter p, i or k: ")
3 Dim city As String = Console.ReadLine()
4 If city = "p" Then
5 Console.WriteLine("Welcome to Penang")
6 ElseIf city = "i" Then
7 Console.WriteLine("Welcome to Ipoh")
8 ElseIf city = "k" Then
9 Console.WriteLine("Welcome to Kedah")
10 End If
11 End Sub

(Assume that the user entered ’i’)

ii. Number program

1 Sub Main()
2 Console.Write("Enter your number: ")
3 Dim number As Integer = Console.ReadLine()
4 If number < 0 Then
5 Console.WriteLine("Negative Number")
6 Else

7

8 If number = 0 Then
9 Console.WriteLine("Zero Number")
10 Else
11 Console . WriteLine ( " Positive Number " )
12 End If
13 End If
14 End Sub

(Assume that the user entered 10)

Activity - Suggested answers

All solutions are available at the remote GitHub repository.

5.3.7 Hands-on: Select structure - Even and odd numbers

Select is another decision structure, highly recommend when we have given constants to compare
with an expression. Suppose that none of the constants matches with the expression, the Case Else

block will then execute.

Suppose we’re making a program that helps us decide whether a number is even or odd. Let us walk
through the following steps to create the program.

102

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 Sub Main()
2 Console.WriteLine("Enter your number")
3 Dim number As Integer
4 number = Console.ReadLine()

5

6 Select Case (number Mod 2)
7 Case 0
8 Console.WriteLine("{0} is an even number", number)
9 Case 1
10 Console . WriteLine ( " {0} is an odd number " , number )
11 Case Else
12 Console . WriteLine ( " Impossible event ! " )
13 End Select
14 End Sub

Use select structure only when we have a defined list of constants that we can compare with the
result of an expression. Otherwise, use If Else{} structure.

3. Suppose that you try running the compiled program, by pressing <F5>, the program will prints

either message ”Even Number” or ”Odd Number” when a number entered.

4. Click on Save All icon to save the work.

5.3.8 Hands-on: Select structure - with numerical value

Note that the select structure allows you to handle program flow based on a predefined set of

choices. For example, the logic of following program prints a specific string message based on one

of two possible selections (the Case Else handles an invalid selection). Let us walk through the

following steps to create the VB program.

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 Sub Main()
2 Console.WriteLine("1 [C#], 2 [VB]")
3 Console.Write("Please pick your language preference: ")
4 Dim n As String = Console.ReadLine()
5 Select Case (n)
6 Case 1
7 Console.WriteLine("Good choice , C# is a fine language.")
8 Case 2
9 Console.WriteLine("Visual Basic .Net: OOP ,

multithreading , and more!")
10 Case Else

103

11 Console . WriteLine ( " Well ... good luck with that ! " )
12 End Select
13 End Sub

Note that VB demands that each case (including Case Else) contains executable statements.

3. Suppose that you try running the compiled program, by pressing <F5>, the program will prints

respective message to the user’s language preference.

4. Click on Save All icon to save the work.

5.3.9 Hands-on: Select structure - with string and other values

The unique feature of the VB select statement is that you can evaluate string data in addition to

numeric data. The select structure of VB supports string, bool, and long data types. Let us walk

through the following steps to create the VB program, which evaluates a string variable.

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 Sub Main()
2 Console.WriteLine("C# or VB")
3 Console.Write("Please pick your language preference: ")
4 Dim langChoice As String = Console.ReadLine()
5 Select Case (langChoice)
6 Case "C#"
7 Console.WriteLine("Good choice , C# is a fine language.")
8 Case "VB"
9 Console.WriteLine("VB: OOP , multithreading and more!")
10 Case Else
11 Console . WriteLine ( " Well ... good luck with that ! " )
12 End Select

13

14 Dim pass As Boolean
15 Console . Write ( " Please enter your marks : " )
16 Dim marks As Double = Console . ReadLine ()
17 If marks >= 40 Then
18 pass = True
19 Else
20 pass = False
21 End If
22 Select Case ( pass )
23 Case True
24 Console . WriteLine ( " Congratulation , you pass the course ! " )
25 Case False
26 Console . WriteLine ( " Sorry , you failed your course . " )
27 Case Else
28 Console . WriteLine ( " Impossible event ! " )
29 End Select

104

30

31 Dim longDecimalValue As Long = 4294967296
32 Select Case ( longDecimalValue )
33 Case 4 _294_967_296
34 Console . WriteLine ( " Decimal . " )
35 Case Else
36 Console . WriteLine ( " Others " )
37 End Select

38

39 Dim l o n g H e x a d e c i m a l V a l u e As Long = 4294967296
40 Select Case ( l o n g H e x a d e c i m a l V a l u e )
41 Case & H1_0000_0000
42 Console . WriteLine ( " Hexadecimal . " )
43 Case Else
44 Console . WriteLine ( " Others " )
45 End Select

46

47 Dim longBinaryValue As Long = 4294967296
48 Select Case ( longBinaryValue )
49 Case & B 1 _ 0 0 0 0 _ 0 0 0 0 _ 0 0 0 0 _ 0 0 0 0 _ 0 0 0 0 _ 0 0 0 0 _ 0 0 0 0 _ 0 0 0 0
50 Console . WriteLine ( " Binary . " )
51 Case Else
52 Console . WriteLine ( " Others " )
53 End Select

54

55 Dim longMixValue As Long = 1 1 29 2 8 10 6 8 65 1 3 70 1 2 4
56 Select Case ( longBinaryValue )
57 Case & H _ 0 F A C _ 0 3 2 6 _ 1 4 8 9 _ D 6 8 C
58 Console . WriteLine ( " Mix . " )
59 Case Else
60 Console . WriteLine ( " Others " )
61 End Select
62 End Sub

3. Suppose that you try running the compiled program, by pressing <F5>, the program will prints

respective message to the user’s language preference.

4. Click on Save All icon to save the work.

5.3.10 Hands-on: Select structure - multiple case statements with same result

Falling through from one case statement to another case statement is not allowed, but what if multiple

case statements should produce the same result? Fortunately, case statements of select structure

can be combined, as the following code. Let us walk through the following steps to create the VB
program.

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

105

1 Sub Main()
2 Dim Year , Month , Day As Integer
3 Dim birthday As Date
4 Try
5 Console.Write("Enter year of your birthday (in integer): ")
6 Year = Console.ReadLine()
7 Console.Write("Enter month of your birthday (in integer): ")
8 Month = Console.ReadLine()
9 Console.Write("Enter day of your birthday (in integer): ")
10 Day = Console . ReadLine ()
11 birthday = New DateTime ( Year , Month , Day )

12

13 Select Case ( birthday . DayOfWeek )
14 Case DayOfWeek . Monday
15 Console . WriteLine ( " Your birthday is on Monday . " )
16 Case DayOfWeek . Tuesday
17 Console . WriteLine ( " Your birthday is on Tuesday . " )
18 Case DayOfWeek . Wednesday
19 Console . WriteLine ( " Your birthday is on Wednesday . " )
20 Case DayOfWeek . Thursday
21 Console . WriteLine ( " Your birthday is on Thursday . " )
22 Case DayOfWeek . Friday
23 Console . WriteLine ( " Your birthday is on Friday . " )
24 Case DayOfWeek . Saturday
25 Console . WriteLine ( " Your birthday is on Saturday . " )
26 Case Else
27 Console . WriteLine ( " Your birthday is on Sunday . " )
28 End Select

29

30 Select Case ( birthday . DayOfWeek )
31 Case DayOfWeek . Monday , DayOfWeek . Tuesday ,

DayOfWeek.Wednesday , DayOfWeek.Thursday ,
DayOfWeek.Friday
32 Console . WriteLine ( " It is on weekday . " )
33 Case Else
34 Console . WriteLine ( " It ’ s the weekend ! " )
35 End Select
36 Catch ex As Exception
37 Console . WriteLine ( " Bad input ! " )
38 End Try
39 End Sub

Note that if any code was included between the case statements, the VB compiler would throw an er-
ror. As long as they are consecutive statements, as shown earlier, case statements can be combined
to share common code.

3. Suppose that you try running the compiled program, by pressing <F5>, the program will prints

respective message to the user’s favourite day.

4. Click on Save All icon to save the work.

106

The select structure also supports using a GoTo to exit a case condition, and execute another
case statement or other line of codes. Here is an example of using the GoTo statement in a switch

block.

1 Sub Main()
2 Dim Year , Month , Day As Integer
3 Dim birthday As Date
4 Try
5 Console.Write("Enter year of your birthday (in integer): ")
6 Year = Console.ReadLine()
7 Console.Write("Enter month of your birthday (in integer): ")
8 Month = Console.ReadLine()
9 Console.Write("Enter day of your birthday (in integer): ")
10 Day = Console . ReadLine ()
11 birthday = New DateTime ( Year , Month , Day )

12

13 Select Case ( birthday . DayOfWeek )
14 Case DayOfWeek . Monday
15 GoTo LineWeekday
16 Case DayOfWeek . Tuesday
17 GoTo LineWeekday
18 Case DayOfWeek . Wednesday
19 GoTo LineWeekday
20 Case DayOfWeek . Thursday
21 GoTo LineWeekday
22 Case DayOfWeek . Friday
23 GoTo LineWeekday
24 Case Else
25 Console . WriteLine ( " It ’ s the weekend ! " )
26 GoTo LineWeekend
27 End Select
28 LineWeekday :
29 Console . WriteLine ( " It ’ s on weekday . " )
30 LineWeekend :
31 Catch ex As Exception
32 Console . WriteLine ( " Bad input ! " )
33 End Try
34 End Sub

5.3.11 Activity

1. Rewrite the following code using the select structure.

1 Console.WriteLine("Enter your number")
2 Dim number As Integer = Console.ReadLine()
3 If (number = 1) Then
4 Console.WriteLine("number = 1")
5 ElseIf (number > 10) Then
6 Console.WriteLine("number > 10")
7 End If

107

2. Rewrite the following code using the select structure.

1 Console.WriteLine("Enter your number")
2 Dim number As Integer = Console.ReadLine()
3 If (number = 1) Then
4 Console.WriteLine("number = 1")
5 End If
6 If (( number >= 2) And (number < 10)) Then
7 Console.WriteLine("number in the range of 2 to 9")
8 End If
9 If (number >= 10) Then
10 Console . WriteLine ( " number >= 10 " )
11 End If

Activity - Suggested answers

All solutions are available at the remote GitHub repository.

5.4 Loops Structure

Keep in mind that the selection (decision) structure is used when we need the computer to make a
decision. The appropriate action will be executed based on the decision. In this section, we explain
the repetition (loops) structure. Loops structure is used when we need the computer to repeatedly

execute program instructions, e.g. for x number of times, until a condition is met. This is referred to

as a loop-continuation condition. We will discuss various loop statements in the this section.

5.4.1 while loop

The while looping construct is useful should you want to execute a block of statements until some
terminating condition has been reached, specifically. Within the scope of a while loop, you will need

to ensure this terminating event is indeed established; otherwise, you will be stuck in an endless

loop. In the following VB, the message ”In while loop” will be continuously printed until the user
terminates the loop by entering yes at the command prompt.

1 Sub Main()
2 Dim userIsDone As String = ""
3 While userIsDone.ToLower <> "yes"
4 Console.WriteLine("In while loop")
5 Console.Write("Are you done? [yes] [no]: ")
6 userIsDone = Console.ReadLine()
7 End While
8 End Sub

In another example, look at the following VB code to find out the first multiple of 2 which is larger than
50. The while statement executes until the condition is false. Example in this case, the statement

’64 is less than or equal to 50’ is evaluated to be false, (64 ≤ 50 is false) causing the loops to be

terminated.

108

1 Sub Main()
2 Console.Write("Enter a number (less than 50): ")
3 Dim number As Integer = Console.ReadLine()
4 While Number < 50
5 Console.Write(Number & "")
6 Number = Number * 2
7 End While
8 End Sub

5.4.2 do-while loop

The do-while loop produces the same result as the while loop statement. Check out the reimple-

mentation code as follows.

1 Sub Main()
2 Dim userIsDone As String = ""
3 Do While (userIsDone.ToLower <> "yes")
4 Console.WriteLine("In do -while loop")
5 Console.Write("Are you done? [yes] [no]: ")
6 userIsDone = Console.ReadLine()
7 Loop

8

9 Console.Write("Enter a number (less than 50): ")
10 Dim number As Integer = Console . ReadLine ()
11 Do While number < 50
12 Console . Write ( number & " " )
13 number = number * 2
14 Loop
15 End Sub

5.4.3 do-until loop

The do-until loop is different from while and do-while loop statements. The do-until loop will

execute repeatedly as long as the condition is false. We demonstrate another version of program to

find the first multiple of 2 which is larger than 50 using a do-until loop statement.

1 Sub Main()
2 Console.Write("Enter a number (less than 50): ")
3 Dim number As Integer = Console.ReadLine()
4 Do Until number > 50
5 Console.Write(number & " ")
6 number = number * 2
7 Loop
8 End Sub

5.4.4 Activity
Answer the following questions.

109

1. Write a pseudocode to execute the loop instructions as long as the value in the variable number is

greater than 8 using a do-while loop statement.

2. Refer to question 1 and rewrite the pseudocode using a do-until loop statement.

3. Write an assignment statement to increase the variable number by 8.

4. Write an assignment statement to decrease the variable number by -8.

5. Determine the output displayed by the following code.

i.
1 Dim number As Integer = 0
2 Do While number < 5
3 Console.Write(number & " ")
4 number = number + 1
5 Loop

ii.
1 Dim number As Integer = 0
2 Do Until number > 5
3 Console.Write(number & " ")
4 number = number + 1
5 Loop

iii.
1 Dim number As Integer = 3
2 Do While number < 15
3 number = 2 * number + 1
4 Loop
5 Console.WriteLine(number)

6. Identify the error in the following code.
1 Dim number As Integer
2 Do While number <> 7
3 number = 0
4 Console.WriteLine(number)
5 number += 1
6 Loop

Activity - Suggested answers

1. The solution is available at the remote GitHub repository.
2. The solution is available at the remote GitHub repository.

3. number = number + 8.
4. number = number - 8.

110

5. The solution is available at the remote GitHub repository.

6. Loop could not terminate. The line number = 0 should appear before the do-while loop state-

ment.

1 Dim number As Integer
2 number = 0
3 Do While number <> 7
4 Console.WriteLine(number)
5 number += 1
6 Loop

5.4.5 for-next loop

When you need to iterate over a block of code a fixed number of times, the for-next loop statement

provides a good deal of flexibility. In essence, you are able to specify how many times a block of code
repeats itself, as well as the terminating condition as shown as follows.

1 Sub Main()
2 Dim number As Integer
3 For number = 1 To 10
4 Console.WriteLine("Number is: {0} ", number)
5 Next
6 End Sub

The control variable in above example was increased by 1 after each pass through the loop. You do
not have to set the loop counter at 1 and increase the control value by 1 each time. You can select

any value you like. In the following VB program, you will learn about using the keyword Step.

1 Sub Main()
2 For number As Integer = 4 To 20 Step 2
3 Console.WriteLine("Number is: {0} ", number)
4 Next
5 End Sub

The condition of for-next loop is evaluated to be true when the initial value of 4 is assigned to the
variable number. When the Next keyword is reached, variable number is increased by 2 on each
loop. Keyword Step will cause the control variable to become 6. The looping continues until the
value 20 has been printed, and the control variable number is increased to 22 causing the condition

to become false and then the loop to be terminated.

The following examples provide you with different ways of writing the control variable in a for-next

loop statement.

i. Control variable from 1 to 10 in increasing step of 1.

For number = 1 To 10 or
For number = 1 To 10 Step 1

ii. Control variable from 10 to 1 in decreasing step of 1.

For number = 10 To 1 Step -1

111

iii. Control variable from 4 to 10 in increasing steps of 2.

For number = 4 To 10 Step 2

iv. Control variable from 10 to 4 in decreasing steps of 2.

For number = 10 To 4 Step -2

v. Control variable over the sequence of the following values: 4, 7, 10, 13, 16.

For number = 4 To 16 Step 3

vi. Control variable over the sequence of the following values: 16, 13, 10, 7, 4.

For number = 16 To 4 Step -3

5.4.6 Activity
Answer the following questions.

1. Write a program to display a table of the first 3 numbers and their squares using a for-next loop

statement.
2. Determine the output displayed on the Console window from the following code.

i.
1 For number As Integer = 4 To 8
2 Console.WriteLine(2 * number)
3 Next

ii.
1 For number As Integer = 4 To 8 Step 2
2 Console.WriteLine(number)
3 Next
4 Console.WriteLine("Number increment by 2")

3. Identify the errors in the following code.
i.
1 For number As Double = 1 To 10.5 Step -1
2 Console.WriteLine(number)
3 Next

ii.
1 For number As Integer = 1 To 10 Step 0.5
2 Console.WriteLine(number)
3 Next

112

Activity - Suggested answers

1. The solution is available at the remote GitHub repository.
2. The solution is available at the remote GitHub repository.
3. The solution is available at the remote GitHub repository.
a. The loop is never executed since 1 is less than 10.5, and the step is negative.
b. Step increment is 0.5, the variable number must assume non-integer values such as decimal
places. The word Integer should be replaced with Double.

5.4.7 do-loop while loop

In the previous section, you have learnt the while and do-while loop statements. The condition of

these loop statements is tested at the beginning of the loop, before the body of the loop is performed.

The do-loop while tests the condition after the loop body is performed (the loop body is always

executed at least once).

1 Sub Main()
2 Dim number As Integer = 1
3 Do
4 Console.Write(number & " ")
5 number += 1
6 Loop While number <= 4
7 End Sub

5.4.8 do-loop until loop

The do-loop until is similar to the do-until loop, except that the condition is tested after the

body is performed (loop body executes at least once) and is repeatedly executed until the condition

is true. The following code demonstrates the printing of the numbers from 1 to 4 using a do-loop
until statement. The loop-termination condition (number > 4) is not evaluated until the body has
been executed at least once. The statement Console.Write(number & " ") will exit from the
loop if the condition (number > 4) is true. The loop will continue executing if the condition (number >

4) is false.

1 Sub Main()
2 Dim number As Integer = 1
3 Do
4 Console.Write(number & " ")
5 number += 1
6 Loop Until number > 4
7 End Sub

5.4.9 exit statement

The Exit Do statement can be executed in a do-while, do-loop while, do-until or do-loop
until statements to cause the program to exit immediately from a loop. The Exit For statement

113

and Exit While statements cause immediate exit from the for-next and while loops respec-

tively.

The following VB program demonstrates the use of Exit For, Exit Do and Exit While in their

respective repetition statements. Note that the first five iterations (values 1 to 5) is false, so the

program control proceeds to line 12, which displays the current value of number. Suppose that
number = 6 is evaluated to be true, then the Exit statement will execute to terminate the loop.

1 Sub Main()
2 Dim number As Integer
3 For number = 1 To 30
4 If number = 6 Then
5 Exit For
6 End If
7 Console.Write(number & " ")
8 Next
9 Console.WriteLine(vbCrLf & "for -next exit from loop at number" &

number & vbCrLf)

10

11 number = 1
12 Do Until number > 45
13 If number = 6 Then
14 Exit Do
15 End If
16 Console . Write ( number & " " )
17 number += 1 ’ increment number
18 Loop
19 Console . WriteLine ( vbCrLf & " do - until exit from loop at number " &

number & vbCrLf)

20

21 number = 1
22 While number <= 60
23 ’ Skip remaining code in loop only if number = 6
24 If number = 6 Then
25 Exit While
26 End If
27 Console . Write ( number & " " )
28 number += 1
29 End While
30 Console . WriteLine ( vbCrLf & " while exit from loop at number " &

number & vbCrLf)

31

32 End Sub

5.4.10 Activity

Answer the following questions.

1. Determine the output of the following code.

114

1 Sub Main()
2 Dim savingBal As Double = 1000
3 Dim interestRate As Double = 1.0
4 Dim counter As Integer = 0
5 Do
6 Console.WriteLine(counter & " " & savingBal)
7 savingBal = (1 + interestRate) * savingBal
8 counter += 1
9 Loop Until (savingBal > 2000)
10 Console . WriteLine ( counter )
11 End Sub

2. Choose the best answer to describe the difference in the execution of the do-until (first set of
code) and the do-loop until (second set of code).

1 Sub Main()
2 ’ first set of code
3 Dim payAmount As Integer = 500
4 Do
5 ’Processing steps
6 payAmt = payAmt - 50
7 Loop Until payAmt > 200
8 Console.WriteLine(payAmt)

9

10 ’ second set of code
11 Dim payAmt As Integer = 500
12 Do Until payAmt > 200
13 ’ Processing steps
14 payAmt = payAmt - 50
15 Loop
16 Console . WriteLine ( payAmt )
17 End Sub

(A) The first loop will not be executed.

(B) The first loop will have one additional 1oop execution compared to the second loop.

(C) There is no difference between the two loops.

(D) The test statements should be payAmt ≥ 150 in the second example so that the loop will be

executed.

Activity - Suggested answers

1. The solution is available at the remote GitHub repository.
2. A

115

5.5 Logical operator

You have studied simple conditions such as number ≥ 10 and number <> 0. Logical operators, such
as And, Or, Xor and Not can be used to form complex conditions by combining simple ones. Examine

examples for each operator as follows.

i. And operator:
The logical And operator ensures that two conditions are both true in a program before a certain

action is executed.

1 If assignmentMark >= 50 And examinationMark >= 50 Then
2 Console.Write("Pass")
3 End If

This condition is evaluated to be true if and only if both the conditions are true. When this
combined condition is true, then print ”Pass” message. However, if either or both conditions are
false, the program skips the ”Pass” message.

Expression 1 Expression 2 Expression 1 And Expression 2
True True
True False True
False True False
False False False
False

ii. Or operator:
The logical Or operator ensures that either or both of the two conditions are true before a certain

action is executed.

1 If gpa >= 4 Or averageMark >= 80 Then
2 Console.Write("Grade A")
3 End If

This condition evaluates to be true if either or both of the conditions are true. ”Grade A” is
always printed, unless both of the conditions are false.

Expression 1 Expression 2 Expression 1 Or Expression 2
True True
True False True
False True True
False False True
False

iii. Xor operator:
Logical Xor operator ensures that the condition is true if and only if one of its operands results

in a true value and the other results in a false value. If both operands are true and both are
false, the entire condition is false.

116

Expression 1 Expression 2 Expression 1 Xor Expression 2
True True
True False False
False True True
False False True
False

iv. Not operator:
Logical Not operator requires only one operand. The Not operator reverses (negates) the

meaning of a condition.

1 If Not (mark >= 50) Then
2 Console.Write("Fail")
3 End If

Expression 1 Not Expression 1
True
False False
True

The following VB program demonstrates the use of the logical operators by displaying their truth

tables.

1 Sub Main()
2 ’Display truth table for And
3 Console.WriteLine("And" & vbCrLf &
4 "True And True: " & (True And True) & vbCrLf &
5 "True And False: " & (True And False) & vbCrLf &
6 "False And True: " & (False And True) & vbCrLf &
7 "False And False: " & (False And False) & vbCrLf)

8

9 ’Display truth table for Or
10 Console . WriteLine ( " Or " & vbCrLf &
11 " True Or True : " & ( True Or True ) & vbCrLf &
12 " True Or False : " & ( True Or False ) & vbCrLf &
13 " False Or True : " & ( False Or True ) & vbCrLf &
14 " False Or False : " & ( False Or False ) & vbCrLf )

15

16 ’ Display truth table for Xor
17 Console . WriteLine ( " Xor " & vbCrLf &
18 " True Xor True : " & ( True Xor True ) & vbCrLf &
19 " True Xor False : " & ( True Xor False ) & vbCrLf &
20 " False Xor True : " & ( False Xor True ) & vbCrLf &
21 " False Xor False : " & ( False Xor False ) & vbCrLf )

22

23 ’ Display truth table for Not
24 Console . WriteLine ( " Not " & vbCrLf &
25 " Not False : " & ( Not False ) & vbCrLf &
26 " Not True : " & ( Not True ) & vbCrLf )
27 End Sub

117

118

5.6 Method

In this section, we focus on methods. There are two types of methods, subroutines and functions, that
are used to break complex problems into smaller problems that can be handled one at a time. We
refer to both subroutines and functions as methods. Methods can eliminate repetitive code and can
be reused in other programs.

Subroutine Function
A subroutine is enclosed by the Sub and End Sub state- A function is enclosed by the Function and End Function
ments. statements.

Private Sub method-name(parameter-list) Function method-name (parameter-list) As data-type
Declarations and statements Declarations and statements
End Sub Return expression
End Function
The subroutine performs a task and then returns control to The function performs a task and then returns control to the
the calling code. When it returns control, it does not return calling code. When it returns control, it also returns a value
a value to the calling method. to the calling method. That is why function contains return-
Example: DisplayMessage type statement where result is returned from the function to
its caller.
Subroutines should change the values of their actual argu- Example: Console.ReadLine
ments Functions should not change the values of their actual ar-
guments

You will learn how to declare a method with more than one parameter and use it in a larger program.
You will also learn how local variables in methods are maintained in memory and how they know
where to return after the method finishes executing. You will learn that a method is used when you
do not need to return a value to the calling code and function is used when you need to return a
value.

In other words, method contains a series of code statements that perform a certain functionality. It
helps to organize code better, eliminates duplication of code, and helps to re-use it over and over
again.

1 Sub MethodName (Parameter_List)
2 //TODO: Method Body // perform its specific tasks
3 End Sub

i. A method is invoked with a statement consisting of a method name and information (list of
parameter, or also known as arguments) that the callee (method being called) requires to do
the tasks. Such statements are referred to as a call statement.

MethodName()

ii. When the method performs its task, it returns control or result to the caller (calling method).
Method has a unique name, which helps to re-use the functionality of code whenever it is called.

We can pass values in methods through parameter list. Method contains a series of code

statements that manipulate data and generate results. If that result has to be used somewhere
else in code, then data has to return where it is called.

119

iii. To make it clearer, look at this analogy for example: A manager (the caller) requests a staff (the
callee) to perform a job and return the report (result) when the job is completed. The manager
does not need to know how the staff performs the specific task. The staff might call other staff
to do the specific task without the manager’s knowledge.

iv. Method Body: Here we write code statements that a method must contain. It executes only

when method is called by its name in code.

The following VB codes shows a method that takes two int values, adds them and returns a result.

Note that the method has a list of parameters. These parameters are adding up in the add variable;
in the next statement, value stored in the variable add is returned. Note, the type of return variable
must match with the (Integer) of the method.

1 Function sumMe(ByVal a As Integer , ByVal b As Integer) As Integer
2 Dim add As Integer = a + b
3 Return add
4 End Function

5

6 Sub printMe(ByVal a As String , ByVal b As Integer)
7 Console.WriteLine("Output: " & b)
8 End Sub

9

10 Sub Main ()
11 Dim number1 As Integer = 3
12 Dim number2 As Integer = 6
13 Dim total1 As Integer = sumMe ( number1 , number2 )
14 printMe ( " total1 : {0} " , total1 )
15 End Sub

5.6.1 Optional Argument

When we define a list of parameters in method’s signature, it becomes compulsory and required to
pass values for all parameters. Optional argument gives us an edge to mark a parameter as optional,
so we can call a method without passing value in optional parameter. All we need to do is to give
some default values to parameters which should be marked as optional. Doing that allows a user to
call a method without passing values to an optional parameter.

Now, look at parameter int b; it has a default value = 2, which helps the user to call MultiplyMe
method without passing the value of ”b”. In that case, ”b” would have a default value = 2. If the user
passes a value of ”b”, then the default value will be overridden with the newest value provided by the

user, as follows.

1 Function multiplyMe(ByVal a As Integer , Optional ByVal b As Integer = 2)
As Integer

2 Dim multiply As Integer = a * b
3 Return multiply
4 End Function

5

6 Sub printMe(ByVal a As String , ByVal b As Integer)

120

7 Console.WriteLine("Output: " & b)
8 End Sub

9

10 Sub Main ()
11 Dim total3 As Integer = multiplyMe (7) ’ a = 7 , b = 2
12 printMe ( " total3 : {0} " , total3 )
13 Dim total4 As Integer = multiplyMe (7 , 3) ’ a = 7 , b = 3
14 printMe ( " total4 : {0} " , total4 )
15 End Sub

5.6.2 Hands-on: Optional Argument - Log data

Optional arguments allows the caller to invoke a single method while omitting arguments deemed
unnecessary, provided the caller is happy with the specified defaults.

1. Suppose that you want to have a method named enterLogData(), which defines a single optional

parameter. Create a new project of Windows Console App (.Net framework) in VB with the installed
Visual Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 Sub enterLogData(ByVal message As String , Optional ByVal owner As String
= "Programmer")

2 Console.Beep()
3 Console.WriteLine("Error: {0}", message)
4 Console.WriteLine("Owner of Error: {0}", owner)
5 End Sub

6

7 Sub Main()
8 enterLogData("Oh no! Grid can ’t find data")
9 enterLogData("Oh no! I can ’t find the payroll data", "CFO")
10 enterLogData ( " Oh no ! I can ’ t find my CGPA " , " Student " )
11 End Sub

In method enterLogData(), the final string argument has been assigned the default value of ”Programmer”,
via an assignment within the parameter definition. Given this, you can call enterLogData() from
within Main() in two ways. Due to the first invocation of enterLogData() did not specify a second

string argument, you would find that the programmer is the one responsible for losing data for the grid,
while the CFO and student misplaced the payroll data and lost the CGPA, respectively, as specified
by the second argument in the second method call.

3. Press <F5> to run the program, and observe the outcomes of program.

4. Click on Save All icon to save the work.

One important thing to be aware of is that the value assigned to an optional parameter must be known
at compile time and cannot be resolved at runtime (if you attempt to do so, you’ll receive compile-time
errors!). Examine the VB codes, which brings compile-time error, as follows.

121

1 Sub enterLogData(ByVal message As String , ByVal owner As String , Optional
timeStamp as DateTime = DateTime.Now)

2 Console.Beep()
3 Console.WriteLine("Error: {0}", message)
4 Console.WriteLine("Owner of Error: {0}", owner)
5 Console.WriteLine("Time of Error: {0}", timeStamp)
6 End Sub

5.6.3 (Default) Pass by Value - Passing Behaviour

The default manner in which a parameter is sent into a function is by value. Suppose that you do not
mark an argument with a parameter modifier, a copy of the data is passed into the function.

1 Function add(ByVal x As Integer , ByVal y As Integer) As Integer
2 Dim answer As Integer = x + y
3 ’ Caller will Not see these changes
4 ’ as you are modifying a copy of the original data.
5 x = 99999
6 y = 88888
7 Return answer
8 End Function

9

10 Sub Main ()
11 ’ Pass two variables in by value .
12 Dim x As Integer = 9 , y = 8
13 Console . WriteLine ( " Before call : X : {0} , Y : {1} " , x , y )
14 Console . WriteLine ( " Answer is : {0} " , add (x , y ) )
15 Console . WriteLine ( " After call : X : {0} , Y : {1} " , x , y )
16 Console . ReadLine ()
17 End Sub

Note that numerical data falls under the category of value types. Therefore, suppose you change the
values of the parameters within the scope of the member, the caller is unaware, given that you are

changing the values on a copy of the caller’s original data. The values of x and y remain identical
before and after the call to add(), as shown in the output, as the data points were sent in by value.
Thus, any changes on these parameters within the add() method are not seen by the caller, as the
add() method is operating on a copy of the data.

5.6.4 Pass by Reference with ByRef Keyword

ByRef keyword helps us to pass an argument by reference. Any change to the parameter’s value

in the method would reflect the same changes to the original variable’s value, where the method’s
argument was being called.

The syntax of passing argument by reference with ”ByRef” keyword is extremely simple. Just write
”ByRef” keyword before defining a parameter in method’s signature and when passing an argument

122

while calling a method. In below code we’re incrementing value of ref parameter by one. The same
changes would reflect to the original variable where method is called.

In the following VB codes, we’re incrementing value of ByRef parameter by one. The same changes
would reflect to the original variable where method is called. Examine definition of passByRef()”
method, ByRef keyword is written before i, which tells us that this parameter would take reference,
not its value. Now also see inside Main () method, where passByRef() is being called. It tells
to pass a reference of ”j” (not the value of ”j”), which is basically a memory address. In the next
statement we print the value of ”j”. Then every change that happens in passByRef()” would affect
the same change in ”j”, which means ”j” value is now 1.

1 Sub passByRef(ByRef i As Integer)
2 i=i+1
3 End Sub

4

5 Sub Main()
6 Dim j As Integer = 0
7 passByRef(j)
8 Console.WriteLine(j) ’j = 1
9 End Sub

5.6.5 Use Array to Pass Unlimited Method Argument

The number of arguments of a method depends upon the length of a parameter list in method’s signa-

ture. For example, in our previous example of ”sumMe” method, we cannot pass more than two values

in its arguments. However, with parameter array we can pass an unlimited number of arguments. The
syntax of using array is simple; just locate an array in the method’s parameter list.

Suppose we are required to make a method which takes unlimited arguments and returns a sum of
all the arguments’ values. In the following VB codes, we observe that an Integer array is located.
The code written in method body is simple and straightforward. It is iterating over all arguments and
adding each one of them with the next value. In the end it returns the sum of all arguments.

1 Function passByRef(ByRef i As Integer()) As Integer
2 Dim add As Integer = 0
3 For item As Integer = 0 To (i.Length - 1)
4 add = add + i(item)
5 Next
6 Return add
7 End Function

8

9 Sub Main()
10 Dim array1 As Integer () = New Integer () {2 , 4 , 6 , 8}
11 Dim total As Integer = passByRef ( array1 ) ’ total = 20
12 Console . WriteLine ( " total : {0} " , total )
13 End Sub

123

Note that a method shouldn’t have more than one parameter array. Suppose that there is more than
one parameter, parameter array should be the last one.

5.6.6 Hands-on: Pass by Array - Calculate average

Let’s hands-on the way to pass parameter array into a method, which consists a variable number of
identically typed parameters (or classes related by inheritance) as a single logical parameter. Such
as, it allows the caller to pass in any number of arguments and return the calculated average.

1. Suppose that you were to prototype a method to take an array of doubles. Create a new project of
Windows Console App (.Net framework) in VB with the installed Visual Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 ’ Return average of "some number" of doubles.
2 Function calculateAverage(ByVal values As Double()) As Double
3 Console.WriteLine("I received {0} doubles.", values.Length)
4 Dim sum As Double = 0
5 If (values.Length = 0) Then
6 Return sum
7 End If
8 For i As Integer = 0 To (values.Length - 1)
9 sum += values(i)
10 Next
11 Return sum
12 End Function

13

14 Sub Main ()
15 ’ Pass in a comma - delimited list of doubles ...
16 Dim average As Double
17 average = calculateAverage ( New Double () {4.0 , 3.2 , 5.7 , 64.22 , 87.2})
18 Console . WriteLine ( " Average of data is : {0} " , average )

19

20 ’ ... Or pass an array of doubles .
21 Dim data As Double () = {4.0 , 3.2 , 5.7}
22 average = calculateAverage ( Data )
23 Console . WriteLine ( " Average of data is : {0} " , average )
24 End Sub

The above VB codes would force the caller to first define the array, then fill the array, and finally pass it

into the method. However, if you define calculateAverage() to take an array of Double, the caller

can simply pass a comma-delimited list of doubles. The .NET runtime will automatically package the

set of doubles into an array of type Double behind the scenes.

3. Press <F5> to run the program, and observe the outcomes of program.

4. Click on Save All icon to save the work.

124

5.6.7 Method Overloading

VB allows a method to be overloaded. Suppose that you define a set of identically named methods
that differ by the number (or type) of parameters, the method in question is said to be overloaded.

Using overloading, you allow the caller to call a single method, e.g. named add(). Again, the key is

to ensure that each version of the method has a distinct set of arguments (methods differing only by
return type are not unique enough). Check out the following VB codes.

1 Function add(ByVal x As Integer , ByVal y As Integer) As Integer
2 Return x + y
3 End Function

4

5 Function add(ByVal x As Double , ByVal y As Double) As Double
6 Return x + y
7 End Function

8

9 Function add(ByVal x As Long , ByVal y As Long) As Long
10 Return x + y
11 End Function

12

13 Sub Main ()
14 ’ Calls int version of Add ()
15 Console . WriteLine ( add (10 , 10) )
16 ’ Calls long version of Add () ( using the New digit separator )
17 Console . WriteLine ( add (900 _000_000_000 , 900 _000_000_000 ) )
18 ’ Calls double version of Add ()
19 Console . WriteLine ( add (4.3 , 4.4) )
20 End Sub

As per above VB codes, the caller invoke add() with the required arguments, and the compiler is

happy to comply, given that the compiler is able to resolve the correct implementation to invoke with
the provided arguments.

5.6.8 Lambda Expression

A lambda expression is a function or subroutine without a name that can be used wherever a delegate
is valid. Lambda expressions can be functions or subroutines and can be single-line or multi-line. You
can pass values from the current scope to a lambda expression. You create lambda expressions

by using the keyword Function or with keyword Sub, just as you create a standard function or

subroutine. However, lambda expressions are included in a statement.

1. Create a new project of Windows Console App (.Net framework) in VB with the installed Visual
Studio.

2. In the source file, i.e. Module1.vb, locate the following lines of VB code.

1 Sub Main()
2 Console.ForegroundColor = ConsoleColor.DarkRed
3 Console.WriteLine("Lambda Expression with function")

125

4 Dim increment1 = Function(x) x + 1
5 Dim increment2 = Function(x)
6 Return x + 2
7 End Function
8 Console.WriteLine(increment1(1)) ’value 2
9 Console.WriteLine(increment2(2)) ’value 4

10
11

12 Console . BackgroundColor = ConsoleColor . White
13 Console . WriteLine ( " Lambda Expression with subroutine " )
14 Dim writeline1 = Sub ( x ) Console . WriteLine ( x )
15 Dim writeline2 = Sub ( x )
16 Console . WriteLine ( x )
17 End Sub
18 writeline1 (3) ’ value 3
19 writeline1 (6) ’ value 6
20 End Sub

Note that the VB code shows both the single-line and multi-line lambda expression syntax for both
function and subroutine. A lambda expression does not have a name.

3. Press <F5> to run the program, and observe the outcomes of program.

4. Click on Save All icon to save the work.

5.7 Summary

We learnt how to manipulate and create GUI controls, including writing VB code to respond to control
events. Mouse-event handling is an example as applied in software like Paint. Lastly, we also learnt
how to use custom control in VB application.
In this topic, we learnt the selection and repetition (loops) structures. These structures are also
called control statements, and they are more complex than sequence structures, which allow us to
control the flow of the building blocks and making decisions. We also learnt how to make the program
loop a specified number of times until all the conditions are satisfied, logical operator and method
formation.

126

6 Topic 6: Windows-based Application Development

6.1 Objectives

By the end of this section, you should be able to:
i. Design and build a graphical Windows application using GUI controls
ii. Create and manipulate GUI controls

6.2 Introduction

This section is a continuation of Graphical User Interfaces (GUIs). Keep in mind that a GUI allows
a user to interact visually with an program through the mouse, keyboard and other forms of input
devices. Microsoft Word is an example of a GUI which consists of various controls, e.g. menus, scroll-

bars and buttons. You have already learnt how to create TextBox, Button, Label, PictureBox and
ListBox controls in Week 1. Suppose that your GUI design is easy to use and follow, the user will

have a productive and enjoyable experience. Otherwise, they will struggle to figure out how to enter
data or which button to click.

Visual Studio contains a wide variety of control objects for use in the GUI. In this section, we are
going to focus on additional advanced controls. You will learn about all these control objects and their
functions throughout this section. Once you are familiar with all these controls, we will guide you on
how to create custom controls which are derived from existing controls. Finally, we will make use
of these controls to support mouse input. You will learn three events (MouseUP, MouseDown and
MouseMove) that enable you to deal with mouse input directly. These controls form a user-friendly
interface. All these control components are located in the Toolbox. You need to access the Toolbox in
order to create controls.

6.3 Graphical User Interface with Windows Forms App

Visual Studio (VS) contains a wide variety of control objects, which are located in the Toolbox, for use
in the GUI as follows.

Table 13: Control Objects.

Button DateTimePicker
GroupBox and Panel ListBox
CheckBox CheckedListBox
RadioButton ComboBox
Tooltips Mouse-event handling
NumberUpDown User defined controls (Custom controls)
Menus

127

6.3.1 Label, TextBox and Button

The following VB program demonstrates the use of a TextBox to obtain the hidden password. The
TextBox that hides the information entered by you is called a password TextBox. When you click on
the ’Show Password’ button, the password will be displayed on the non-editable TextBox.

Reminder:
i. A label displays text that cannot be directly modified. It is modified via the Text property.

ii. TextBox can display text and allows the user to type text via the keyboard. If you set the
PasswordChar property to the asterisk character (*), the TextBox becomes a password TextBox.

6.3.2 Activity
Answer the following questions.

1. A GUI allows you to interact with the application program visually. True/False?

2. You need a password for Textbox to enable the Password property. True/False?

3. Which of the following is an example of a GUI?
(A) Windows 2000
(B) Firefox
(C) Visual Studio 2019
(D) All of the above

4. What is the difference between TextBox and Label?
(A) TextBox has a scrollbar
(B) Label cannot be changed during runtime
(C) Label has a scrollbar

(D) Both of them are the same

5. What would a password TextBox display if the user entered the password as wawasan?

(A) w*****

128

(B) waw***
(C) *******
(D) None of the above
Activity - Suggested answers
1. True
2. False, the Password property means that the text entered is changed to a different character to
prevent others from seeing the entered text.
3. D
4. C
5. C
6.3.3 GroupBox and Panel

GroupBox and Panel are used to group related set of controls in a GUI. All the controls within a
GroupBox or Panel move together when the GroupBox or Panel is moved. Suppose that you hide
the GroupBox or Panel, the attached controls follow as a unit.

Reminder:

i. GroupBox can display a caption (e.g., Languages) and does not include scrollbars.
ii. Panel cannot display a caption but can include scrollbars.

6.3.4 Activity
Answer the following questions.

1. GroupBoxes have a text display and a scrollbar. True/False?

129

2. Panels have scrollbars if the contents get larger. True/False?
3. What is the effect of setting the following property to the value? grpGroupBox.Text = "Visual";
4. The AutoScroll property will cause a Panel to scroll to the bottom if the controls displayed

are too large. True/False?

Activity - Suggested answers

1. False. A GroupBox does not have scroll bars but it does have a Text property.

2. True

3. The word ”Visual” becomes the caption embedded at the top of grpGroupBox.
4. False. AutoScroll simply inserts scrollbars if needed.

6.3.5 CheckBox

A CheckBox is a small square box that is either blank or contains a check mark. When you click a
CheckBox (value True), a check mark appears in the box. Suppose that you click the CheckBox again
(value False), the check mark is removed. CheckBox allows you to select more than one option at
a time. During runtime, when you click on the CheckBox to check (select) it, the CheckedChanged

event occurs.
The following program allows the cashier to calculate the cost of various items. Examine the VB code
as available at GitHub.

Reminder:

During runtime, you click on the CheckBoxes to toggle between the checked and unchecked states.
The four CheckedChanged events will be triggered in the match event handler. Examine the com-
puted total in Total Amount Payment by checked all four CheckBoxes.

6.3.6 RadioButton

RadioButtons are similar to CheckBoxes. RadioButtons usually appear in groups, and only one
button can be selected at one time. Selecting one RadioButton in a group forces all others to be

130

deselected. RadioButtons are also referred to as option buttons because they only allow you to
select one option from multiple options. A RadioButton is on when a solid dot appears in the circle.

For example, in the statement:

i. btnRadioButton.Checked = true
Turns on btnRadioButton and turns off all other buttons.

ii. btnRadioButton.Checked = false
Turns off btnRadioButton and has no effect on the other buttons.

Reminder:

During runtime, the CheckedChanged event is triggered when a RadioButton is turned on or

off.

6.3.7 Activity value
Answer the following questions.

1. CheckBoxes and RadioButtons are used to:

(A) let the user choose between the given choices.
(B) let the user select any given options.
(C) enter data.
(D) All of the above.

2. Suppose that a CheckBox or RadioButton is selected, its property contains the
true.

(A) On
(B) Checked
(C) Off
(D) Boolean

131

3. RadioButtons can be used inter-changeably with CheckBoxes. True/False?
4. Only one RadioButton can be checked in a form. True/False?

5. What is the effect of the following statements?
1 chkCheckBox.Checked = True
2 chkCheckBox.Checked = False
3 chkCheckBox.Text= "&Visual"

6. Determine the state of the two RadioButtons after the button is clicked.

1 radRadio1.Checked = True
2 radRadio2.Checked = True

Activity - Suggested answers
1. A
2. B

3. False. RadioButtons can only have one option selected in the group whereas many CheckBoxes

can be selected at once.

4. False. Suppose that grouped in Panels or GroupBoxes, more than one RadioButton per form

can be checked.

5. The chkCheckBox CheckBox becomes checked. The chkCheckBox CheckBox becomes
unchecked. The word Visual becomes the caption following with the CheckBox, and V be-
comes the hot key for accessing the CheckBox.

6. RadRadio2 is checked and radRadio1 is unchecked.

6.3.8 Tooltips

ToolTips are helpful descriptive text that appears whenever the mouse hovers over the GUI control.

It serves as useful reminders for each icon or control. The following VB program demonstrates the

use of ToolTip component to add tool tips to your application. Now you may examine the prepared
VB code to create the ToolTips, as available at GitHub.

132

6.3.9 Activity
Answer the following questions.

1. What is the purpose of a ToolTip?

(A) To allow the mouse to blink while hovering over an item in a GUI.
(B) To allow the mouse tips to be highlighted while hovering over an item in a GUI.
(C) To display helpful text while the mouse hovers over an item in a GUI.
(D) None of the above.

2. When you add a ToolTip component from the Toolbox, it appears on the Form. True/False?

Activity - Suggested answers
1. C

2. False. When adding a ToolTip component from the Toolbox, it appears in the component tray.

6.3.10 NumberUpDown

The NumericUpDown control is used to limit a user’s input choices to a specific range of numeric
values. It appears as a TextBox with two small buttons on the right side - one with an up arrow and

one with a down arrow. You can type numeric values or click the up and down arrows (increasing or

decreasing the value in the control). The following VB program uses the NumericUpDown control to
demonstrate the housing loan interest rate calculation. In this application, we use the TextBoxes to
input the principal and interest rate amounts while NumericUpDown is used to input the number of

years for repayment schedule.

133

Reminder:

i. Set Maximum and Minimum properties to specify the largest and smallest value in range.
ii. Set the Increment property to specify the increment for the current number to change when

you click the control’s up and down arrows.

iii. Set ReadOnly property to true so that you cannot type a number into the control.

iv. You now can only click the up or down arrows to change values in the control.

6.3.11 Activity
Answer the following questions.

1. Which of the following controls would you choose to restrict a user from choosing a specific
range of numeric values?

(A) NumericUpDown
(B) GroupBox
(C) ListBox
(D) TextBox
2. The NumericUpDown appears as a TextBox with two small buttons on the right side: one with

an up arrow and one with a down arrow. True/False?

Activity - Suggested answers
1. A
2. True.

134

6.3.12 Menus

Menus are a list of related items or commands for Windows applications. The commands can be

selected to trigger an event. For example, New and Open are common commands in Microsoft Word.
New and Open are referred to as menu items. A menu item can contain a sub-menu. The main menu

is considered to be the parent of the sub-menu. Menu items can have shortcuts or hotkeys, which

are accessed by pressing the <Alt> key and the underlined letter. For example, <Alt> + <E> will
expand the Edit menu. Some menu items display check marks, indicating that multiple options can

be selected at once. We will learn all these features in the following example.

One good point about VB is that it allows you to create standard menus that are pulled down from the
menu bar without writing the code. You are only required to write the event procedure for menus. To

create a menu, you need a MenuStrip control.

The following VB program uses the MenuStrip control to demonstrate the menus and sub-menus.

The program allows you to manipulate the picture by using menus. Later on, we will add in features
such as using check marks, inserting separator bars and shortcut keys. Let’s examine the prepared
VB code to create and manipulate the menus and sub-menus, as available at GitHub.

6.3.13 Activity

Answer the following questions.

1. Menus are groupings of similar commands. True/False?

2. You use the dollar sign ($) to set an underline shortcut in a menu. True/False?

3. VB program cannot creates sub-menus. True/False?

4. What is the effect of executing the following statements?

mnuMenu.Checked = True
mnuMenu.Checked = False
mnuMenu.Text = "Visual"

5. Write a statement to remove the check mark in front of the menu item named mnuItem.

Activity - Suggested answers

1. True

2. False, the ampersand key (&) is used before the desired letter.

3. False

4. A check mark appears in front of the mnuMenu menu item.
The menu item mnuMenu appears without a check mark to its left.
The text appearing on the mnuMenu item will be changed to Visual.

5. mnuItem.Checked = False

135

6.3.14 DateTimePicker

DateTimePicker control displays the calendar when you click the down arrow. The function of
DateTimePicker is to retrieve date and time information. The following VB program demonstrates
the use of the DateTimePicker control to choose an item’s drop-off date. For example, you are

renting DVD movies via an online movie-rental store. You select a drop-off date from the application
program, and then the estimated delivery date is displayed to you (i.e., the estimated time that the
DVDs will arrive at your home). In the program, we set the delivery date on the next five working-days
excluding the ordering day (presume no public holiday).

Now you may examine prepared VB program to create the DateTimePicker control, as available at

GitHub.
Reminder:

i. Use frmDateTimePicker Load event to limit the range, e.g. to prevent user to select a drop-off
day before the current day (today), or more than a month in advance
dteDateTimePicker.MinDate = DateTime.Today
dteDateTimePicker.MaxDate = DateTime.Today.AddMonths(1)

6.3.15 Activity
Answer the following questions.

1. Which of the following events should you choose when a value is selected in the DateTimePicker

control?

(A) ValueChanged
(B) DateTimeModified
(C) DateModified
(D) TimeModified
2. The DateTimePicker is only limited to displaying up to a year’s selection at a time. True/False?

Activity - Suggested answers
1. A

136

2. False. DateTimePicker control may display more than a year’s selection.

6.3.16 ListBox

ListBoxes are used to display a single column of strings, referred to as items. You can view and
select zero, one, or more than one choice of items in a list. We are using the Items.Add method to
add information to a ListBox. You can also remove and clear all the items added to a ListBox using
Items.RemoveAt and Items.Clear methods respectively. The following VB program demonstrates
the use of Items.Add, Items.RemoveAt and Items.Clear methods with a ListBox object.

Try to examine the prepared VB code to create the ListBox control, as available at GitHub.

6.3.17 Activity
Answer the following questions.

1. Choose the correct syntax to add a new item to a ListBox.
(A) lstListBox.Items.Add(name)
(B) lstListBox.Add(name)
(C) lstListBox.Items.Insert(name)
(D) lstListBox.Insert(name)

2. Choose the correct syntax to clear a list of all values in a ListBox.
(A) lstListBox.Items.Clear()
(B) lstListBox.Items.DeleteItems.All()
(C) lstListBox.Clear()
(D) lstListBox.Items.DeleteAll()

3. Choose the following statement to close the application program.

137

(A) Exit()
(B) unload()
(C) Application.Exit()
(D) Application.Unload()

4. Based on the lstListBox below, determine the effect of the codes. Assume the Sorted property

is set to True and item Tiger is selected.

i. lstBox.Items.Add("Chicken")
ii. lstBox.Items.Remove("Lion")
iii. lstBox.Items.RemoveAt(0)
iv. lstBox.Items.RemoveAt(lstBox.SelectedIndex)

Activity - Suggested answers
1. A
2. A
3. C
4. Sample answers are as follows.

i. The item Chicken is inserted into lstListBox between Cat and Dog.
ii. Lion is deleted from the list.
iii. The first item, Cat is removed from lstListBox.
iv. The currently selected item in lstListBox, Tiger is deleted.

6.3.18 CheckedListBox

The CheckedListBox control is derived from the class ListBox and includes a CheckBox next

to each item. You can select multiple items at one time. The following Vb program demonstrates

the use of CheckedListBox and ListBox to display a student’s registration of subjects. In the
CheckedListBox, you can select multiple subjects such as C#, VB, Java, C, Python, Perl and Ruby.
The ListBox will display your selections.

138

Try walk through the prepared Vb code to create the CheckedListBox control, as available at

GutHub.

6.3.19 Activity
Answer the following questions.

1. Which of the following is used to add an item to a CheckedListBox?
(A) Add method
(B) AddRange method
(C) String Collection Editor

(D) All of the above

2. The itemCheck event occurs in CheckedListBox when an item is either checked or unchecked.

True/False?

3. Class CheckedListBox is derived from class ListBox and contains similar properties. True/-

False?

Activity - Suggested answers
1. D
2. True
3. True

6.3.20 ComboBox

The ComboBox control combines TextBox features with a drop-down list. By default, you can either
enter text into TextBox or just select the appropriate item from a list. The item is then displayed at
the top of the ComboBox. A scrollbar will appear if the list contains more items in the drop-down list.
A ComboBox can save space on a form because, unlike the ListBox, the full list of choices can be
hidden in a ComboBox.
VB provides three styles of ComboBoxes. The style is controlled by the ComboBox’s DropDownStyle

property, which can be set to Simple, DropDown (the default), or DropDownList. In the following VB

139

program, we demonstrate the use of the DropDownStyle ComboBox to get a person’s title (Dr., Mr. or

Ms.) for the person’s name.

Reminder:
When the DropDownStyle property is set to:

i. DropDownList, the text portion of the ComboBox cannot be edited, and you must click the list

arrow to display the list of choices.

ii. Simple, the text portion of the ComboBox can be edited and the list portion is always displayed.
iii. DropDown, the text portion of the ComboBox can be edited, and you must click the list arrow to

display the list of choices.

Try to walk through the prepared VB code to create the DropDownList ComboBox, as available at

GitHub.
6.3.21 Activity
Answer the following questions.

1. The ComboBox cboCombo is shown as follow. Assume the Sorted property is set to True, and

item ”Tiger” is selected. Give a statement to carry out the stated task.

i. Highlight the item Cat.
ii. Highlight the third item of the list.
iii. Delete the item Lion.
iv. Insert the item Elephant.

2. Which of the following property determines the style of the ComboBox?

(A) DropComboStyle
140

(B) DropDownStyle
(C) DropStyle
(D) TypeStyle

3. Class CheckedListBox is derived from class ListBox and contains similar properties. True/-

False?

4. You use the DropDownList style of a ComboBox to prevent a user from entering items. True/-

False?

Activity - Suggested answers
1. Sample answers are as follows.

i. cboCombo.Text = (cboCombo.Items[0].ToString())
ii. cboCombo.Text = (cboCombo.Items[2].ToString())
iii. cboCombo.Items.Remove("Lion")
iv. cboCombo.Items.Add("Elephant")

Explore more at URL https://docs.microsoft.com/en-us/dotnet/framework/
winforms/controls/add-and-remove-items-from-a-wf-combobox

2. B
3. True

6.3.22 Mouse-event handling
Example of mouse events are clicks, presses and moves. It will be generated when you interact with
a control through the mouse. Information about the event is passed to the event-handling method

through an object of class System.Windows.Forms.MouseEventArgs such as mouse pointer’s

x- and y- coordinates, mouse button pressed and clicked) is used to create the mouse-event han-
dler.
The following VB program demonstrates of different mouse events to draw the path of the mouse on

a Panel. A line segment is added to the GraphicsPath for each MouseMove and MouseDown events
that occur. To update the graphics, the Invalidate method is called for the Panel on each MouseDown
and MouseUp event. In addition, the graphic path is scrolled up or down when the MouseWheel event
occurs. Additional mouse events, e.g. MouseHover, are identified on screen as well.

141

6.3.23 Activity
Answer the following questions.

1. Which of the following events is triggered when the mouse is moved downward?
(A) MouseUp
(B) MouseDown
(C) MouseMove
(D) MouseOver

2. MouseUp and MouseDown events are used when the mouse moves up or down. True/False?
3. Mouse interaction with the GUI is limited to click, press, and move. True/False?

Activity - Suggested answers
1. C
2. False
3. False. There is a variety of interactions the mouse can perform; however, they can all be
grouped into these three basic categories, i.e. click, press and move.

6.3.24 User Control
VB allows you to create your own custom controls. The custom control that you created will appear in
the ToolBox and can be added to Forms. Creating a custom control allows you to:

i. Reuse the same control throughout the application, so saving on code.
ii. Keep code relating to a control within the control’s class. You do not need to handle the event

in.

142

Note that UserControlClock class contains a Label and a Timer. Whenever the Timer raises an event
(one per second), the Timer’s event handler updates the Label to reflect the current time. There are
no event handlers in frmClock, we show only the code for UserControlClock as the prepared VB code
at GitHub.

6.4 Summary

We learnt how to manipulate and create GUI controls, including writing VB code to respond to various
control events. Mouse-event handling is an example as applied in software like Paint. Lastly, we also
learnt how to use custom control in VB application.

143

7 Topic 7: Advanced Windows-based Application Development

7.1 Objectives

By the end of this section, you should be able to:
i. Use the Windows Presentation Foundation (WPF) to draw simple shapes
ii. Apply simple SQL queries
iii. Generate database connections and create LINQ to SQL objects

7.2 Introduction

This section is a continuation of Graphical User Interfaces (GUIs) with the Windows Presentation
Foundation (WPF). It also allows a user to interact visually with an program through the mouse, key-

board and other forms of input devices, which is not limited to TextBox, Button, Label, PictureBox
and ListBox as you learned in previous section.

In this section, you will take your first look at the architecture of WPF and the coordinate system used
by VS. We will then introduce you on how to draw lines, rectangles, ellipses and polygons using WPF.
Next, we will use transforms to manipulate images. All of us are familiar with multimedia elements like
audio and video. These elements add interactivity to an application. So, in this section, we will also
learn to include audio video components to an application.
Note that WPF is a graphical display system for Windows. It is designed for .NET, influenced by
modern display technologies such as HTML and Flash, and hardware accelerated. Note that It is also
the most radical change to hit Windows user interfaces since Windows 95.

7.3 Windows Presentation Foundation (WPF)

A standard Windows application relies on two well-worn parts of the Windows operating system (OS)
to create its user interface:

• User32: This provides the familiar Windows look and feel for elements, e.g. windows, buttons
and text boxes.

• GDI/GDI+: This provides drawing support for rendering shapes, text, and images at the cost of
additional complexity.

Over the years, both technologies have been refined, and the Application Programming Interfaces
(APIs) that developers use to interact with them have changed dramatically. However, whether you’re
crafting an application with .NET and Windows Forms or with Visual Basic (VB) 6 or MFC-based C++
code, behind the scenes the same parts of the Windows OS are at work. Newer frameworks simply
deliver better wrappers for interacting with User32 and GDI/GDI+.

144

7.3.1 WPF and DirectX

Microsoft created one way around the limitations of the User32 and GDI/GDI+ libraries: DirectX. Di-
rectX began as a cobbled-together, error-prone toolkit for creating games on the Windows platform. Its
design mandate was speed, and so Microsoft worked closely with video card vendors to give DirectX
the hardware acceleration needed for complex textures, special effects, e.g. partial transparency, and
three-dimensional (3D) graphics.

Over the years since it was first introduced (shortly after Windows 95), DirectX has matured. It’s now
an integral part of Windows, with support for all modern video cards. However, the programming API
for DirectX still reflects its roots as a game developer’s toolkit. Due to its raw complexity, DirectX is
almost never used in traditional types of Windows applications, e.g. business software.

WPF changes all this. In WPF, the underlying graphics technology isn’t GDI/GDI+. Instead, it’s Di-
rectX. Remarkably, WPF applications use DirectX no matter what type of user interface you create.
That means that whether you’re designing complex 3D graphics (DirectX’s forte) or just drawing but-
tons and plain text, all the drawing work travels through the DirectX pipeline. As a result, even the most
mundane business applications can use rich effects such as transparency and anti-aliasing. You also
benefit from hardware acceleration, which simply means DirectX hands off as much work as possible
to the graphics processing unit (GPU), which is the dedicated processor on the video card.

In technical, DirectX is more efficient. DirectX understands higher-level ingredients, e.g. textures and
gradients that can be rendered directly by the video card. However, GDI/GDI+ doesn’t. GDI/GDI+
needs to convert them to pixel-by-pixel instructions, which are rendered much more slowly by modern
video cards. In other words, WPF is not a wrapper for GDI/GDI+. Instead, it’s a replacement - a
separate layer that works through DirectX. For your attention, WPF still relies on User32 for certain
services, e.g. handling and routing input and sorting out which application owns which portion of
screen real estate. However, all the drawing is funnelled through DirectX.

7.3.2 WPF and Hardware Acceleration

On the other hand, WPF offers hardware acceleration through DirectX, and it has a compelling im-
provement by including a basket of high-level services designed for program development. Having a
high-powered video card is not an absolute guarantee that you’ll get fast, hardware accelerated per-
formance in WPF. Software also plays a significant role. For example, WPF can’t provide hardware
acceleration to video cards that are using out-of-date drivers. (If you’re using an older video card,
these out-of-date drivers are quite possibly the only ones that were provided in the retail package.)
Windows it can take advantage of the Windows Display Driver Model (WDDM). WDDM offers several
important enhancements on old OS, e.g. the Windows XP Display Driver Model (XPDM). Most im-
portantly, WDDM allows several GPU operations to be scheduled at once, and it allows video card
memory to be paged to normal system memory if you exceed what’s available on the video card.

In short, the goal of WPF is to off-load as much of the work as possible on the video card so that
complex graphics routines are render-bound (limited by the GPU) rather than processor-bound (limited
by your computer’s CPU). As such, we keep the CPU free for other work, we make the best use of

145

our video card, and we are able to take advantage of performance increases in newer video cards as
they become available.

WPF is intelligent enough to use hardware optimizations where possible. However, it has a software
fallback for everything. Suppose that you run a WPF application on a computer with a legacy video
card, the interface will still appear the way you designed it. The software alternative may be much
slower, and you will notice that computers with older video cards won’t run rich WPF applications
very well, especially ones that incorporate complex animations or other intense graphical effects. In
practice and remedy, you might choose to scale down complex effects in the GUI, depending on the
level of hardware acceleration that’s available in the client.

7.3.3 WPF and Resolution Independence

Traditional Windows applications are bound by certain assumptions about resolution. Developers
usually assume a standard monitor resolution (e.g. 1024 by 768 pixels), design their windows with
that in mind, and try to ensure reasonable resizing behaviour for smaller and larger dimensions. The
problem is that these applications aren’t scalable. As a result, suppose that we use a high monitor
resolution that crams pixels in more densely, our application windows become smaller and more
difficult to read. This is particularly a problem with newer monitors that have high pixel densities
and run at correspondingly high resolutions. For example, it’s common to find consumer monitors
(particularly on laptops) that have pixel densities of 120 dpi or 144 dpi (dots per inch), rather than the
more traditional 96 dpi. At their native resolution, these displays pack the pixels in much more tightly,
creating eye-squintingly small controls and text. Ideally, applications would use higher pixel densities
to show more detail. For example, a high resolution monitor could display similarly sized toolbar icons
but use the extra pixels to render sharper graphics. That way, we could keep the same basic layout
but offer increased clarity and detail. For a variety of reasons, this solution hasn’t been possible in the
past. Although we can resize graphical content that’s drawn with GDI/GDI+, User32 (which generates
the visuals for common controls) doesn’t support true scaling.

WPF doesn’t suffer from this problem because it renders all user interface elements itself, from simple
shapes to common controls such as buttons. As a result, suppose that we create a button that’s 1
inch wide on our computer monitor, it can remain 1 inch wide on a high-resolution monitor - WPF will
simply render it in greater detail and with more pixels. This is the big picture, but it glosses over a few
details. Most importantly, we need to realize that WPF bases its scaling on the system DPI setting,
not the DPI of your physical display device. This makes perfect sense - after all, if we’re displaying our
application on a 100-inch projector, we’re probably standing several feet back and expecting to see
a jumbo-size version of our windows. We don’t want WPF to suddenly scale down our application to
”normal” size. Similarly, if we’re using a laptop with a high-resolution display, we probably expect to
have slightly smaller windows - it’s the price we pay to fit all your information onto a smaller screen.
Furthermore, different users have different preferences. Some want richer detail, while others prefer
to cram in more content. So, how does WPF determine how big an application window should be?
The short answer is that WPF uses the system DPI setting when it calculates sizes.

146

7.3.4 WPF Units

A WPF window and all the elements inside it are measured using device-independent units. A single
device-independent unit is defined as 1/96 of an inch. To understand what this means in practice, we’ll
need to consider an example. Imagine that we create a small button in WPF that’s 96 by 96 units in
size. Suppose that we’re using the standard Windows DPI setting (96 dpi), each device-independent
unit corresponds to one real, physical pixel, as follows. Essentially, WPF assumes it takes 96 pixels
to make an inch because Windows tells it that through the system DPI setting. However, the reality
depends on your display device.

1 [Physical Unit Size]
2 = [Device -Independent Unit Size] x [System DPI]
3 = 1/96 inch x 96 dpi
4 = 1 pixel

For example, consider a 19-inch LCD monitor with a maximum resolution of 1600 by 1200 pixels.
Using a dash of Pythagoras, you can calculate the pixel density for this monitor, as follows. Note that
the pixel density works out to 100 dpi, which is slightly higher than what Windows assumes. As a
result, on this monitor a 96-by-96-pixel button will be slightly smaller than 1 inch.

1 [ Screen DP√I ]
16002 +12002 pixels
2 = 19inches

3 = 100 dpi

On the other hand, consider a 15-inch LCD monitor with a resolution of 1024 by 768. As the pixel
density drops to about 85 dpi, the 96-by-96 pixel button appears slightly larger than 1 inch.

In both these cases, suppose that we reduce the screen size (say, by switching to 800 by 600 reso-
lution), the button (and every other screen element) will appear proportionately larger. That’s due to
the system DPI setting remains at 96 dpi. In other words, Windows continues to assume it takes 96
pixels to make an inch, even though at a lower resolution it takes far fewer pixels.

7.3.5 WPF and System DPI

Note that computer monitors are designed to work best at a specific resolution, which is called the
native resolution. Suppose that we lower the resolution, the monitor must use interpolation to fill in
the extra pixels, which can cause blurriness. To get the best display, it’s always best to use the native
resolution. Suppose that we want larger windows, buttons, and text, consider modifying the system
DPI setting instead. WPF respects the system DPI setting natively and effortlessly. For example, if
you change the system DPI setting to 120 dpi (a common choice for users of large high-resolution
screens), WPF assumes that it needs 120 pixels to fill an inch of space. WPF translates its logical
units to physical device pixels:

1 [Physical Unit Size]
2 = [Device -Independent Unit Size] x [System DPI]
3 = 1/96 inch x 120 dpi
4 = 1.25 pixel

147

In short, as we set the system DPI to 120 dpi, the WPF rendering engine assumes one device-
independent unit equals 1.25 pixels. Suppose that we show a 96-by-96 button, the physical size will
actually be 120 by 120 pixels (because 96 x 1.25 = 120). This is the result we expect - a button
that’s 1 inch on a standard monitor remains 1 inch in size on a monitor with a higher pixel density.
WPF uses device-independent-units for everything it displays, including shapes, controls, text, and
any other ingredient we put in our WPF application. As a result, we can change the system DPI to
whatever we want, and WPF will adjust the size of our application seamlessly.

7.3.6 WPF and XAML

XAML (short for Extensible Application Markup Language and pronounced as ”zammel”) is a markup
language used to instantiate .NET objects 12. Although XAML is a technology that can be applied to
many different problem domains, its primary role in life is to construct WPF user interfaces. In other
words, XAML documents define the arrangement of panels, buttons, and controls that make up the
windows in a WPF application.

Developers realized long ago that the most efficient way to tackle complex, graphically rich applica-
tions is to separate the graphical portion from the underlying code. That way, artists can own the
graphics, and developers can own the code. Both pieces can be designed and refined separately,
without any versioning headaches. Recall the process of designing a Windows Forms application
with custom graphics in a team setting, we’ve put up with a lot of frustration. Even if the interface
is designed from scratch by a graphic designer, we’ll need to re-create it with VB code. Usually,
the graphic designer will simply prepare a mock-up that you need to translate painstakingly into your
application.

WPF solves this problem with XAML. When designing a WPF application in Visual Studio, the window
we’re designing isn’t translated into code. Instead, it’s serialized into a set of XAML tags. When you
run the application, these tags are used to generate the objects that compose the user interface.
Note that WPF doesn’t require XAML. There’s no reason Visual Studio couldn’t use the Windows
Forms approach and create code statements that construct your WPF windows. Suppose that if it did,
our window would be locked into the Visual Studio environment and available to programmers only.
In other words, XAML opens up worlds of possibilities for collaboration, because other design tools
understand the XAML format. For example, a designer can use a tool, e.g. Expression Design 13, to
fine-tune the graphics in our WPF application or a tool, e.g. Expression Blend 14, to build sophisticated
animations for it.

XAML is not only created to tackle the problem of design collaboration, it also needed to be fast. XML-
based formats, e.g. XAML, are flexible and easily portable to other tools and platforms, they aren’t
always the most efficient option. XML was designed to be logical, readable, and straightforward, not
compact. WPF addresses this shortcoming with Binary Application Markup Language (BAML). Note
that BAML is a binary representation of XAML. When we compile a WPF application in Visual Studio,

12https://en.wikipedia.org/wiki/Extensible_Application_Markup_Language
13https://en.wikipedia.org/wiki/Microsoft_Expression_Design
14https://en.wikipedia.org/wiki/Microsoft_Blend

148

all our XAML files are converted into BAML, and that BAML is then embedded as a resource into the
final DLL or EXE assembly. BAML is tokenized, which means lengthier bits of XAML are replaced with
shorter tokens. BAML is relatively smaller in its size, and it is also optimized in a way that makes it
faster to parse at runtime. The conversion of XAML to BAML is performed by the compiler and it is
done behind the scenes inside Visual Studio. However, it is possible to use XAML without compiling
it first. It happens in scenarios that require some of the user interface to be supplied just in time,
e.g. pulled out of a database as a block of XAML tags. You’ll see how this works later in the next
section.

Note that XAML plays the same role for Windows applications as control tags do for ASP.NET web ap-
plications. The difference is that the ASP.NET tagging syntax is designed to look like HTML, so design-
ers can craft web pages using ordinary web design applications, e.g. FrontPage 15 and Dreamweaver
16. As with WPF, the actual code for an ASP.NET web page is usually placed in a separate file to
facilitate this design. We will learn more in the Unit 4.

There are several different ways using the XAML. The language of XAML is an all-purpose XML-
based syntax for representing a tree of .NET objects. These objects could be buttons and text boxes
in a window or custom classes we’ve defined. In fact, XAML could even be used on other platforms

to represent non-.NET objects too! There are several subsets of XAML as reported at https://
rcosic.wordpress.com/2009/06/08/variants-of-xaml/, as follows.

• WPF XAML: it encompasses the elements that describe WPF content, e.g. vector graphics,
controls, and documents. It’s the most significant application of XAML.

• XPS XAML: it is the part of WPF XAML that defines an XML representation for formatted
electronic documents. It’s been published as the separate XML Paper Specification (XPS)

standard. You may explore more on it at https://en.wikipedia.org/wiki/Open_XML_
Paper_Specification.

• Silverlight XAML: it is a subset of WPF XAML that’s intended for Silverlight applications. Sil-
verlight is a cross-platform browser plug-in that allows us to create rich web content with two-
dimensional graphics, animation, and audio and video.

• WF XAML: it encompasses the elements that describe Windows Workflow Foundation (WF)

content. You can learn more about WF at https://en.wikipedia.org/wiki/Windows_
Workflow_Foundation.

7.3.7 Loading and Compiling XAML

As we have learned, XAML and WPF are separate in complementary and technologies. It is possible
to create a WPF application that doesn’t use the faintest bit of XAML. There are three distinct methods
of coding style that you can use to create a WPF application:

15https://en.wikipedia.org/wiki/Microsoft_FrontPage
16https://en.wikipedia.org/wiki/Adobe_Dreamweaver

149

1. Code-only: This is the traditional approach used in Visual Studio for Windows Forms applications.
It generates a user interface through code statements.

This development style is a less common (but still fully supported) avenue for writing a WPF application
without any XAML. The obvious disadvantage to code-only development is that it has the potential to
be extremely tedious. WPF controls don’t include parameterized constructors, so even adding a
simple button to a window takes several lines of code. One potential advantage is that code-only
development offers unlimited avenues for customization. For example, you could generate a form full
of input controls based on the information in a database record, or you could conditionally decide to
add or substitute controls depending on the current user. All you need is a sprinkling of conditional
logic. By contrast, when you use XAML documents, they’re embedded in your assembly as fixed,
unchanging resources.

2. Code and uncompiled markup (XAML): This is a specialized approach that makes sense in
certain scenarios, where you need highly dynamic user interfaces. You load part of the user inter-

face from a XAML file at runtime using the XamlReader class, as an example in C# and VB .Net
development environment. It offers a way by parsing XAML on the fly with the XamlReader from the
System.Windows.Markup namespace.

The XAML file is distributed alongside the application executable, in the same folder. However, even
though it isn’t compiled as part of the application, you can still add it to your Visual Studio project.
Doing so allows you to manage the file more easily and design the user interface with Visual Stu-
dio (assuming you use the file extension .xaml so Visual Studio recognizes that it’s a XAML docu-
ment).

Suppose that you use this approach, just make sure that the loose XAML file isn’t compiled or em-
bedded in your project like a traditional XAML file. After you add it to your project, select it in the
Solution Explorer, and use the Properties window to set the Build Action to None and the Copy to
Output Directory to ”Copy always”.

Obviously, loading XAML dynamically won’t be as efficient as compiling the XAML to BAML and
then loading the BAML at runtime, particularly if your user interface is complex. However, it opens
up a number of possibilities for building dynamic user interfaces. For example, you could create
an all-purpose survey application that reads a form file from a web service and then displays the
corresponding survey controls (labels, text boxes, check boxes, and so on). The form file would be an

ordinary XML document with WPF tags, which you load into an existing form using the XamlReader.

To collect the results once the survey is filled out, you simply need to enumerate over all the input
controls and grab their content. Another advantage of the loose XAML approach is that it allows you
to use the refinements, e.g. as stated in the XAML 2009 standard and later.

3. Code and compiled markup (BAML): This is the preferred approach for WPF and the one that
Visual Studio supports. You create a XAML template for each window, and this XAML is compiled into
BAML and embedded in the final assembly. At runtime the compiled BAML is extracted and used to
regenerate the user interface. This method has advantages as follows.

• Some of the plumbing is automatic. There’s no need to wire up event handlers in code.

150


Click to View FlipBook Version