You are on page 1of 33

Visual Basic.

NET

Events
Objectives

• this lecture will cover:


– event-driven programming and the event loop
– different types of events
– accessing the Code Window and using its features
– implementing simple event handlers
– correcting simple syntax errors
– the program development cycle
– pseudo-code solutions for simple problems

Visual Basic Slide 2 of 42


Event-driven programming

• program waits until an event occurs


• User controls the program
• An event can occur in 3 ways:
– The user doing something (e.g. Click a button)
– Something happening within the computer (e.g.
System shutdown)
– Something happening within the program (e.g.
Program crash)
• Determine which "things" respond to which
events
– Write code to be executed when event occurs to
perform an action e.g. Calculate the average of a
series of numbers

Visual Basic Slide 3 of 42


Events in VB

• Events occur to objects on a form or the form


– Activate events: user selects item on screen
– Changed events: control property modified
– Focus events: control gets or loses focus
– Key events: user interacts with keyboard
– Mouse events:user interacts using mouse
• One user event can result in many program
events

Visual Basic Slide 4 of 42


Event loop

continuously monitors events

• if event handler exists, it is executed

Visual Basic Slide 5 of 42


Event handlers

Event handlers have:


header identifies event handler
body contains statements to be executed

Private Sub btnPress_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _ header
Handles btnPress.Click
'statements that form the body of event handler
'statement
End Sub

body

Visual Basic Slide 6 of 42


Method header
• Name of the event handler
– defaults to control name, underscore and event
– can be modified but normally left unchanged
• Control and event involved in brackets
– sender: details of control affected
• used if one handler is used for several events
– e: details of event such as character typed or mouse
location
• Events that will be handled by the method
– can add events to be handled

Visual Basic Slide 7 of 42


Accessing Code Window
• Code is viewed using the Code Window
– Project code block automatically generated
– All project code must be between Public Class and
End Class
• Code Window has 2 drop-down combo boxes:
– Class Name: list of all objects in the Solution
– Method Name: list of all events associated with
current object

Event Type

Visual Basic Slide 8 of 42


Editor features

• useful features:
– standard clipboard operations automatic indentation
of code
– spacing of statements
– capitalisation of keywords
– ensuring consistent capitalisation of names
– auto code completion
– collapsible methods
– colour coding

Visual Basic Slide 9 of 42


Running Applications

• Program is run by either:


– Clicking the Start Debugging
icon
– Pressing F5 or

• IDE:
– Compiles or builds program
• Traps any syntax errors
• Displays message box if errors occur
– Creates an executable file in the bin | Debug folder

Visual Basic Slide 10 of 42


Run-time vs. Design-time

• At design time, the programmer can:


– Add controls
– Set control properties
– Add code to controls
– Edit code
• In run-time mode the form is locked
– can only respond to user input

Visual Basic Slide 11 of 42


Coding Event Handlers

• Code in event handler executed each time the


event occurs
• Programmer:
– Adds required code to handlers
– Runs program to check that correct actions are taken
when the events occur

Visual Basic Slide 12 of 42


Adding Comments to Code

• Comments improve readability of code


• To add a comment use the ‘ (single quote)
character or the keyword REM
• Can also use the toolbar to comment statements
Comment / Uncomment Toolbar Icons
Private Sub btnPress_Click(...)
Handles ...
'comment
'statements to be executed
End Sub

Visual Basic Slide 13 of 42


Types of properties

• Appearance
• Behaviour
• Size & position

properties can
be displayed
alphabetically or
categorized

Visual Basic Slide 14 of 42


Changing properties at runtime

• Code can modify properties at runtime


• Assignment ( = ) statement specifies:
– control name followed by a dot
– property to be modified
– new value

Private Sub btnPress_Click(...) Handles ...


'disable btnPress
btnPress.Enabled = False
End Sub

Visual Basic Slide 15 of 42


Changing Color Properties

• Color class contains approximately 140


predefined colors
• Accessed by specifying:
– class name Color followed by a dot
• E.g. Color.Red
– required colour
Private Sub btnPink_Click(...) Handles ...
'change background colour
lblPink.BackColor = Color.HotPink
End Sub

Visual Basic Slide 16 of 42


Changing Text property

• Strings are enclosed in double quotes


• Any number of strings can be concatenated
using the & operator
• vbNewline moves to start of next line

Private Sub btnConcatenate_Click (...) Handles ...


'display Visual Basic on separate lines in label
lblConc.Text = "Visual" & vbNewline & "Basic"
End Sub

Visual Basic Slide 17 of 42


Changing Form properties

• Form properties are modified using the keyword


Me
• The keyword Me refers to the current form

Private Sub btnFormColour_ Click (...) Handles ...


'change form background
Me.BackColor = Color.BlanchedAlmond
End Sub

Visual Basic Slide 18 of 42


Handling multiple events

• same method can be executed when a number


of events occur
• all events to be handled are listed after Handles
keyword

Private Sub btnEither_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnOne.Click, btnTwo.Click
'report button pressed
lblPressed.Text = "Button pressed"
End Sub

Visual Basic Slide 19 of 42


Determining object

• Object that triggered event is held in sender


• This can determine which object was used

Private Sub btnEither_Click( _


ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles btnOne.Click, btnTwo.Click
'report button pressed
lblPressed.Text = sender.Name & " pressed"
End Sub

Visual Basic Slide 20 of 42


Errors in code

• Some errors are recognized by the IDE i.e.


Syntax error
• Some may not become apparent until the
program is executed i.e. Logic error and
Compiler error
• Correcting errors can be difficult:
– explanation of error may be difficult to understand due
to the technical terminologies used
– Location of error may not be exactly as indicated by
the compiler

Visual Basic Slide 21 of 42


Syntax errors

• Misspelled words and missing punctuation


• Normally trapped by IDE as they are typed
– explanation shown when cursor held over error
– should be corrected before running program
• Compiler traps uncorrected syntax errors
– message box prompts user to continue – should
select 'No'
– Error List window displays compilation errors

Visual Basic Slide 22 of 42


Run-time errors

• Program can not run as required


– invalid calculation
– attempt to open a non-existent file
• Only apparent when program runs
• IDE displays a message box:
– nature of error
– Approximate location of error (line number)

Visual Basic Slide 23 of 42


Logic (Semantic) Errors

• Errors program logic


• Not trapped as IDE only checks structure
• Can cause the program to:
– crash
– hang
– continue but produce unexpected results
• Only discovered during program execution when
input data is entered
• Testing can show that code has errors
• Debugging is finding and correcting errors

Visual Basic Slide 24 of 42


Using the debugger

• Facilities to:
– Set breakpoints in code
– Halt execution at statement before breakpoints
– Examine values in the code
– Step through and execute individual lines

Visual Basic Slide 25 of 42


Program development

• Stage 1: Design screens


– ensure screens are logical and easy to follow
• Stage 2: Design pseudo-code
– decide what happens when
• Stage 3: Implement screens
– place controls on form
– change initial appearance
– attach code to events
• Stage 4: Test and debug program

Visual Basic Slide 26 of 42


Worked example - Greetings

• Display or clear a "Hello" message in a label


when the relevant command is clicked
• User should not be able to:
– use "Display" command when message is visible
– use "Clear" command when no message displayed
• "Exit“ method is required to terminate the
program

Visual Basic Slide 27 of 42


Design screens

• Single screen with 3 buttons and 1 label

lblGreetings Hello

Display Clear Exit

btnDisplay btnClear btnExit

Visual Basic Slide 28 of 42


Design pseudo-code

• When btnDisplay button is clicked:


– Set Text of lblGreetings to "Hello"
– Enable btnClear button
– Disable btnDisplay button
• When btnClear button is clicked:
– Set Text of lblGreetings to ""
– Enable btnDisplay button
– Disable btnClear button
• When btnExit button is clicked:
– End the program

Visual Basic Slide 29 of 42


Implement screens and code

• Invoke Visual Basic


• Click New Project button on Start Page
• Enter details of new project
• Create interface
• Set properties
• Attach program code

Visual Basic Slide 30 of 42


Private Sub btnDisplay_Click(...) Handles btnDisplay.Click
‘display greeting
lblGreetings.Text = "Hello"
btnClear.Enabled = True
btnDisplay.Enabled = False
End Sub
Private Sub btnClear_Click(…) Handles btnClear.Click
‘clear greeting
lblGreetings.Clear()
btnDisplay.Enabled = True
btnClear.Enabled = False
End Sub
Private Sub btnExit_Click(…)Handles btnExit.Click
‘end program
End
End Sub

Visual Basic Slide 31 of 42


Test program
• Run program and ensure:
– Clear button initially disabled
– Greetings label initially blank
• Click Display button and ensure:
– Hello displayed in Greetings label
– Display button becomes disabled
– Clear button becomes enabled
• Click Clear button and ensure:
– Hello cleared from Greetings label
– Display button becomes enabled
– Clear button becomes disabled
• Click Exit button and ensure:
– program ends

Visual Basic Slide 32 of 42


Summary

• This lecture has covered:


– the principles of event-driven programming
– writing code to handle events that occur within a
program
– finding and correcting syntax errors
– the stages involved in developing a program

Visual Basic Slide 33 of 42

You might also like