CIT - 206 - Lecture - 2 - Introduction To Event Driven Programming

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

Lecture Two-Events Programming Basics, 2022

Introduction To Event Programming, CIT 206, Mr.


Thobius Joseph, UoI
______________

EVENTS PROGRAMMING BASICS


Learning Objectives
1. Describe events programming and events
2. Describe Visual Studio IDE interfaces (For Simplicity in class we will use VS2010
instead of VS2019 but to advance is very easy)
3. Understanding basic in VB.NET controls (or components)
4. Describing and writing
- Data types
- Variables
- Modifiers
- Dim statement (Declaration statement)
- Conditional Operators
- Logical Operators
- Looping statements
- Decision Structures
- Procedures
 General Procedures
 Event Procedures
- Functions
- Parameters
5. Event Handling
- Events
- Events Handles
1. Conditional Operators

Conditional operators resemble mathematical operators. These operators allow a


Visual Basic program to compare data values and then decide what actions to be
taken. They are also known as numerical comparison operators. They are used to
compare two values to see whether they are equal, one value is greater than the other
value or one value is less than the other value. Condition expressions are created by
using condition operators.

Operator Description
= Equal to

Example:
Dim 1a as Integer = 2
Dim 1b as Integer = 3
1a = 1b (Condition)
Answer is false
> Greater than

Example:
Dim 1a as Integer = 2
Dim 1b as Integer = 3
1a > 1b (Condition)
Answer is false
< Less than

Example:
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI
Dim 1a as Integer = 2
Dim 1b as Integer = 3
1a < 1b (Condition)
Answer is True
>= Equal to or
Greater
Than

Example:
Dim 1a as Integer = 2
Dim 1b as Integer = 3
1a >= 1b (Condition)
Answer is false
<= Less
than
or
Equal to

Example:
Dim 1a as Integer = 2
Dim 1b as Integer = 3
1a <= 1b (Condition)
Answer is true

<> Not equal to

Example:
Dim 1a as Integer = 2
Dim 1b as Integer = 3
1a < > 1b (Condition)
Answer is True

NB: During character comparison refer to the ASCII table decimal


representation therefore,

Upper case letters are less than lowercase letters, “A”<”B”<”C”<”D”…….<”Z” and
number are less than letters.

2. Logical Operators

In certain cases, we might need to make more than one comparisons to arrive
at a decision. In this case, using numerical comparison operators alone might
not be sufficient and we need to use the logical operators, as shown in Table
below Logical operators can be used to compare numerical data as well as
non-numeric data such as strings.

Table 13.2: Logical Operators


Operator Description
And Both sides must be true
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

Example:
Dim 1a as Integer = 2
Dim 1b as Integer = 3
Dim 1c as Integer = 4
(1a < 1b) And (1c < > 1a)
Answer is true
One side or other must be true

Example:
Dim 1a as Integer = 2
Or
Dim 1b as Integer = 3
Dim 1c as Integer = 4
(1a > 1b) Or (1c < > 1a)
Answer is False
One side or other must be true but not both

Example:
Dim 1a as Integer = 2
Xor
Dim 1b as Integer = 3
Dim 1c as Integer = 4
(1a < 1b) Xor (1c < > 1a)
Answer is true
Negates true

Example:
Dim 1a as Integer = 2
Not
Dim 1b as Integer = 3
Dim 1c as Integer = 4
Not (1c < 1a)
Answer is true

3. Looping Statements (or Loop Structures)

This statements or structures allow you to run one or more lines of code
repetitively. We can write a code in Visual Basic that allows the program to
run repeatedly until a condition or a set of conditions is met. This is code
statements are known as loops. Looping is a very useful feature of Visual
Basic because it makes repetitive works easier. You can repeat the statements
in a loop structure until

 A condition is True
 A condition is False
 A specified number of times
 Once for each element in a collection.

VB.NET supports the following loop statements:

1. Do loop
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI
2. For Next
3. For Each Next
4. While End While
5. With End With

Inside Loop statements code are executed one by one but you can use special
kind of statements known as control statements to change order of which code
is executed. The control statements in VB.NET are given below:

1. Exit Statement
2. Continue Statement
3. GoTo Statement

The Do...Loop construction allows you to test a condition at either the beginning
or the end of a loop structure. You can also specify whether to repeat the loop
while the condition remains True or until it becomes True.

Do { While | Until } condition


[ statements ]
// [ Continue Do ]
[ statements ]
// [ Exit Do ]
[ statements ]
Loop

' -or-

Do
[ statements ]
//[ Continue Do ]
[ statements ]
// [ Exit Do ]
[ statements ]
Loop { While | Until } condition

The Do Loop statements have four different forms, as shown


below:

a)
Do While condition
Block of one or more VB statements
Loop
b)
Do
Block of one or more VB statements
Loop While condition
c)
Do Until condition
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI
Block of one or more VB statements
Loop
d)
Do
Block of one or more VB statements
Loop Until condition

Parts
Term Definition
Do Required. Starts the definition of the Do loop.
While Required unless Until is used. Repeat the loop until condition is False.
Until Required unless While is used. Repeat the loop until condition is True.
condition Optional. Boolean expression. If condition is Nothing, Visual Basic treats it
as False.
statements Optional. One or more statements that are repeated while, or
until, condition is True.
Continue Optional. Transfers control to the next iteration of the Do loop.
Do
Exit Do Optional. Transfers control out of the Do loop.
Loop Required. Terminates the definition of the Do loop.

The Do...Loop structure gives you more flexibility than the


While...End While Statement because it enables you to decide whether
to end the loop when condition stops being True or when it first
becomes True. It also enables you to test condition at either the start or
the end of the loop

Example 1
Create a Form with any name, add button with name BtnDoLoop, then
under its event procedure add below code: Then debugging the form
by place run debugging

Dim index As Integer = 0


Do
MessageBox.show (index.ToString & " ")
index += 1
Loop Until index > 10

' Output: Messagebox will appear 10 times

Re write above do loop by using while instead of until

Dim index As Integer = 0


Do While index <= 10
MessageBox.show(index.ToString & " ")
index += 1
Loop
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI
' Output: Messagebox will be shown 10 times
4. For Next
The For....Next Loop event procedure is written as follows:

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next
Example

Create a Form with any name, add button with name BtnForNext, then
under its event procedure add below code: Then debugging the form
by place run debugging

Dim counter As Integer

For counter = 1 To 1000 Step 10

counter = counter + 1

MessageBox.show (counter)

Next

Re write above For Next loop code

For counter=1000 to 5 step -5

counter=counter-10

Beep()

Next

Re write above For Next loop code

For n=1 to 10

MessageBox.Show(“For Next Loop”)

Next

Re write above For Next loop code

5. For Each Next

The For Each...Next construction runs a set of statements once for each element in
a collection. You specify the loop control variable, but you do not have to
determine starting or ending values for it.

For Each element [ As datatype ] In group


Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

[ statements ]

//[ Continue For ]

[ statements ]
// [ Exit For ]
[ statements ]
Next

Parts
Term Definition
element Required in the For Each statement. Optional in the Next statement.
Variable. Used to iterate through the elements of the collection.
datatype
Optional if Option Infer is on (the default) or element is already
declared;
required if Option Infer is off and element isn't already declared.
The data type of element.
group Required. A variable with a type that's a collection type or Object.
Refers to the collection over which the statements are to be repeated.
statements Optional. One or more statements between For Each and Next that run
on each item in group.
Continue For Optional. Transfers control to the start of the For Each loop.
Exit For Optional. Transfers control out of the For Each loop.
Next Required. Terminates the definition of the For Each loop.

Example
' Create a list of strings by using a collection initializer.

Dim lst As New List(Of String) _


From {"abc", "def", "ghi"}

' Iterate through the list.

For Each item As String In lst


MessageBox.show (item & " ")
Next

'Output: abc def ghi

6. While End While

The While...End While construction runs a set of statements as long as the


condition specified in the While statement is True.

While condition

[ statements ]
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

//[ Continue While ]

[ statements ]

//[ Exit While ]

[ statements ]

End While

Parts
Term Definition
condition Required. Boolean expression. If condition is Nothing, Visual Basic treats
as False.
statements Optional. One or more statements following While, which run every
time condition is True.
Continue Optional. Transfers control to the next iteration of the While block.
While
Exit While Optional. Transfers control out of the While block.
End While Required. Terminates the definition of the While block.

Example

In the following example, the statements in the loop continue to run


until the index variable is greater than 10.

Dim index As Integer = 0

While index <= 10

MessageBox.Show(index.ToString & " ")


index += 1

End While

‘Output: 0 1 2 3 4 5 6 7 8 9 10
2. Decision structures

Visual Basic lets you test conditions and perform different operations depending on
the results of that test. You can test for a condition being true or false, for various
values of an expression. In order to do that you will use decision statements (In C++
they are called conditional.)

Following is the general form of a typical decision making structure


found in most of the programming languages –
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

VB.Net provides the following types of decision making statements

Statement Description

If ... Then statement An If...Then statement consists of a boolean


expression followed by one or more
statements.

You can use a single-line version if you have


just one test and one statement to run. If you
have a more complex set of conditions and
actions, you can use the multiple-line version
and terminates the statement by using End If
clause
Syntax:
' Single-line syntax:
If condition Then
[ statements ]
Example:
' If A > 10, execute the MessageBox
statement in the order

If A > 10 Then
MessageBox.Show("It is greater than ")
' Multiple-line syntax:
If condition Then
[ statements ]
End if
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

Example:
' If A > 10, execute the MessageBox
statement in the order

If A > 10 Then
MessageBox.Show(" It is greater than ")
End if

If...Then...Else statement An If...Then statement can be followed by an


optional Else statement, which executes
when the boolean expression is false. This
statement is also terminated by using End If
clause in case of multiple-line conditions.
Syntax:
' Multiline syntax:
If condition [ Then ]
[ statements ]
[ ElseIf elseifcondition [ Then ]
[ elseifstatements ] ]
[ Else
[ elsestatements ] ]
End If

Example:
Dim randomizer As New Random()
'set our variable
Dim count As Integer =
randomizer.Next(0, 5)

Dim message As String

'If count is zero, output will be no


items
If count = 0 Then
message = "There are no items."
'If count is 1, output will be
"There is 1 item.".
ElseIf count = 1 Then
message = "There is 1 item."
'If count is greater than 1, output
will be "There are {count} items.", where
{count} is replaced by the value of count.
Else
message = $"There are {count}
items."
End If

You can use one If or Else if statement inside


nested If statements
another If or Else if statement(s). Both the
inside and outside if statements should end
with End If clause
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

Syntax:
No General syntax just put one if statement
inside another if statement as shown in below
example

Example:
' Determine the current day of week and hour
of day.
Dim dayW As DayOfWeek =
DateTime.Now.DayOfWeek
Dim hour As Integer =
DateTime.Now.Hour

' Return True if Wednesday from 2 to


3:59 P.M.,
' or if Thursday from noon to 12:59
P.M.
If dayW = DayOfWeek.Wednesday Then
If hour = 14 Or hour = 15 Then
Exit if
Else
Messagebox.Show("True")
End If
ElseIf dayW = DayOfWeek.Thursday
Then
If hour = 12 Then
Exit if
Else
MessageBox.Show("False")
End If
Else
MessageBox.Show("Done")
End If

Select Case statement A Select Case statement allows a variable to


be tested for equality against a list of values.
Syntax:
Select [ Case ] testexpression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Example:
Dim number As Integer = 8
Select Case number
Case 1 To 5
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

MessageBox.Show("Between 1 and 5,
inclusive")
' The following is the only Case
clause that evaluates to True.
Case 6, 7, 8
MessageBox.Show("Between 6 and 8,
inclusive")
Case 9 To 10
MessageBox.Show("Equal to 9 or 10")
Case Else
MessageBox.Show("Not between 1 and
10, inclusive")
End Select

nested Select Case statements You can use one select case statement inside
another select case statement(s).
Example:
Try put select case inside select case

Try...Catch...Finally Allow you to run a set of statements under an


environment that retains control if any one of
your statements causes an exception. You can
take different actions for different exceptions. It
is also known as Error handling statement.
Syntax:
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When
expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
Example:
' Declare variables.
Dim x As Integer = 5
Dim y As Integer = 0

' Set up structured error handling.


Try
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI

' Cause a "Divide by Zero"


exception.
x = x \ y

' This statement does not execute


because program
' control passes to the Catch block
when the
' exception occurs.
MessageBox.Show("end of Try block")
Catch ex As Exception
' Show the exception's message.
MessageBox.Show(ex.Message)

' Show the stack trace, which is a


list of methods
' that are currently executing.
MessageBox.Show("Stack Trace: " &
vbCrLf & ex.StackTrace)
Finally
' This line executes whether or not
the exception occurs. It is optional you may
not write finally block of code
MessageBox.Show("in Finally block")
End Try
Example 2: Without Finally block
Try
Dim result As String ="100"
MessageBox.Show("Result: " & result)
Catch ex As Exception
MessageBox.Show("Exception Message:
" & ex.Message)
End Try

Tutorial

1. Create a form and insert a text box and rename it as txtNum and a button
and rename it as OK. Write the code so that when the user runs the
program and enter a number that is greater than 100, he or she will see
the “You win a lucky prize” message. On the other hand, if the number
entered is less than or equal to 100, the user will not see any message.

2. This program can compute the grade for the mark entered by the user. Is
uses several Else If statements and the logical operator And to achieve
the purpose.

3. Which Decision statement is used in below statement:

Dim a As Integer
Dim b As Integer
a = 3
Lecture Two-Events Programming Basics, 2022
Introduction To Event Programming, CIT 206, Mr.
Thobius Joseph, UoI
b = 4
If a > b Then
MsgBox ("a is greater then b")
Else
MsgBox ("b is greater then a")
End If

NB: Select Case and try Catch Finally is not your level. Read them fou
your passions.

You might also like