Final Jimjim Oop - Learning Module - Final
Final Jimjim Oop - Learning Module - Final
MODULE FOUR
November 2021
Weeks 16-18
I. Course Overview
This course pack is specifically produced for the course CS 212 (Object Oriented
Programming) intended for the students of SDSSU Main campus enrolled in the Bachelor of
Science in Computer Science (BSCS) program. This is the fourth module for the final term period.
Applications of VB.Net Exception, File Handling and Basic Controls as well as
discussions with examples about VB.Net Dialog Boxes, Advanced Forms and Event Handlings
are tackled and presented in this course pack.
II. General Instruction
The content of the module covers topics for weeks 16-18 for Final Term period. This
Module is composed of five (5) parts. The first part pertains to the Intended Learning Outcomes
(ILOs) followed by the course direction where students are directed to focus their respective
course works. The nitty-gritties of the course are on the third part of the module which includes
the lecture and discussion proper. Each student taking this course is also required to answer all the
assessment tasks to measure whether the student have learned from the lessons. It is for the
students to grasp all the essentials of the topics covered in a particular lesson. Links, urls, videos
and other supplementary reading materials are provided in this module.
Academic honesty is required of all students. Plagiarism--to take and pass off as one’s own
work, the work or ideas of another--is a form of academic dishonesty. Penalties may be assigned
for any form of academic dishonesty” (See Student Handbook/College Manual). Sanctions for
breaches in academic integrity may include receiving a grade of an “Failed” on a test or
assignment. In addition, the Director of Student Affairs may impose further administrative
sanctions.
IV. Introduction
The first two(2) topics for week 16 are discussions with examples for VB.Net VB.Net
Exception and File Handling and Basic Controls. It is then followed by discussion/presentation of
Video Tutorials are also available for the learners to review and better understand the
course content included in Module 4.
WEEK 16
Understand and discuss when it is appropriate to apply or use VB.Net Exception Handling
Compile and execute sample code for Error File Handling
What is an Exception?
An exception is an unwanted error that occurs during the execution of a program and can
be a system exception or application exception. Exceptions are nothing but some abnormal and
typically an event or condition that arises during the execution, which may interrupt the normal
flow of the program.
Keywor Description
d
Try A try block is used to monitor a particular exception that may throw an exception within the
application.
And to handle these exceptions, it always follows one or more catch blocks.
Catch It is a block of code that catches an exception with an exception handler at the place in a
program
Finally It is used to execute a set of statements in a program, whether an exception has occurred.
problem.
o A user has entered incorrect data or performs a division operator, such as an attempt to
divide by zero.
o A connection has been lost in the middle of communication, or system memory has run
out.
Exception Handling
When an error occurred during the execution of a program, the exception provides a way to
transfer control from one part of the program to another using exception handling to handle the
error. VB.NET exception has four built-in keywords such as Try, Catch, Finally, and Throw to
handle and move controls from one part of the program to another.
In VB.net, there are various types of exceptions represented by classes. And these exception
classes originate from their parent's class 'System. Exception'.
The following are the two exception classes used primarily in VB.NET.
1. System.SystemException
2. System.ApplicationException
System.SystemException: It is a base class that includes all predefined exception classes, and
some system-generated exception classes that have been generated during a run time such
as DivideByZeroException, IndexOutOfRangeException, StackOverflowExpression, and so on.
1. Try
2. ' code or statement to be executed
3. [ Exit Try block]
4. ' catch statement followed by Try block
5. Catch [ Exception name] As [ Exception Type]
6. [Catch1 Statements] Catch [Exception name] As [Exception Type]
7. [ Exit Try ]
8. [ Finally
In the above syntax, the Try/Catch block is always surrounded by a code that can throw
an exception. And the code is known as a protected code. Furthermore, we can also use multiple
catch statements to catch various types of exceptions in a program, as shown in the syntax.
Let's create a program to handle an exception using the Try, Catch, and Finally keywords
for Dividing a number by zero in VB.NET programming.
TryException.vb
Module module1
Sub divExcept(ByVal a As Integer, ByVal b As Integer)
Dim res As Integer
Try
res = a \ b
' Catch block followed by Try block
Catch ex As DivideByZeroException
Console.WriteLine(" These exceptions were found in the program {0}", ex)
' Finally block will be executed whether there is an exception or not.
Finally
Console.WriteLine(" Division result is {0}", res)
End Try
End Sub
Sub Main()
divExcept(5, 0) ' pass the parameters value
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
Lets' create a program using the Try-Catch statement in VB.NET to handle the exceptions.
Try_catch.vb
Imports System
Module module1
Sub Main(ByVal args As String())
Dim strName As String = Nothing
Try
If strName.Length > 0 Then ' it throws and exception
Console.WriteLine(" Name of String is {0}", strName)
End If
Catch ex As Exception ' it catches an exception
Console.WriteLine(" Catch exception in a program {0}", ex.Message)
End Try
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Output:
1. Throw [ expression ]
Imports System
Module thowexcept
Sub Main()
Try
Throw New ApplicationException("It will throw a custom object exception")
Catch ex As Exception
Console.WriteLine(" Custom Exception is: {0}", ex.Message)
Finally
Console.WriteLine("Finally block statement executes whether there is an exception
or not.")
End Try
Console.WriteLine(" Press any key to exit")
Console.ReadKey()
End Sub
End Module
Output:
Therefore, a good programmer should be more alert to the parts of the program that
could trigger errors and should write errors handling code to help the user in managing the
errors. Writing errors handling code is a good practice for Visual Basic 2017 programmers, so do
not try to finish a program fast by omitting the error handling code. However, there should not be
too many errors handling code in the program as it might create problems for the programmer to
maintain and troubleshoot the program later.
Visual Basic 2019 has improved a lot in its built-in errors handling capabilities compared
to Visual Basic 6. For example, when the user attempts to divide a number by zero, Visual Basic
Visual Basic 2019 still supports the vb6 errors handling syntax, that is the On Error GoTo
program_label structure. Although it has a more advanced error handling method, we shall deal
with that later. We shall now learn how to write errors handling code in Visual Basic 2019. The
syntax for errors handling is
In this example, we will deal with the error of entering non-numeric data into the text
boxes that suppose to hold numeric values. The program_label here is error_handler. When the
user enters non-numeric values into the text boxes, the error message will display the phrase "One
or both of the entries is/are non-numeric!". If no error occurs, it will display the correct answer.
Try it out yourself.
The Code
Exit Sub 'To prevent error handling even the inputs are valid
error_handler:
Lbl_Answer.Text = "Error"
Lbl_ErrMsg.Visible = True
Lbl_ErrMsg.Text = " One or both of the entries is/are non-numeric! Try again!"
End Sub
Visual Basic 2017 has adopted a new approach in handling errors or rather exceptions handling. It
is supposed to be more efficient than the old On Error Goto method, where it can handle various
types of errors within the Try…Catch…End Try structure.
Try
statements
End Try
The Code
Try
firstNum = TxtNum1.Text
secondNum = TxtNum2.Text
answer = firstNum / secondNum
Catch ex As Exception
Lbl_Answer.Text = "Error"
Lbl_ErrMsg.Visible = True
Lbl_ErrMsg.Text = " One of the entries is not a number! Try again!"
End Try
End Sub
Weeks 17-18
In Visual Basic 2019, there are many kinds of controls that you can use to build a VB
2019 app. The controls can be divided into many categories, namely Common Controls,
Containers, Menus and Toolbar, Data, Components, Printing, Dialogs and WPF
Interoperability. The controls are available in the Toolbox, as shown in Figure 5.1.
TextBox
In this lesson, you will learn how to work with some of the common controls in Visual
Basic 2017. Among the common controls are the label, text box, button, list box, combo box,
Example
In this application, add two text boxes and a button to the Form. Change the text of the button
to ADD. Next, click on the button and enter the following code:
End Sub
This program will add the value in TextBox1 and the value in TextBox2 and displays the sum in a
message box.
Figure 5.3
The Label
The label can be used to provide instructions and guides to the user as well as to
display the output. It is different from the TextBox because it can only display static text,
which means the user cannot change the text. Using the syntax Label.Text, it can display
text and numeric data. You can change its text in the properties window or program it to
change at runtime.
In this lesson, we shall learn how to code for two more controls, the ListBox, and the
ComBox. Both controls are used to display a list of items. However, they differ slightly in the
way they display the items. The ListBox displays the items all at once in a text area whilst the
ComboBox displays only one item initially and the user needs to click on the handle of the
ComboBox to view the items in a drop-down list.
ListBox
The function of the ListBox in visual basic 2019 is to display a list of items. The user can
click and select the items from the list. Items can be added at design time or at runtime. The items
can also be removed at design time and also at runtime.
After clicking on the OK button, the items will be displayed in the ListBox, as shown in Figure
6.2
Items can also be added at runtime using the Add( ) method. Visual Basic 2019 is an
object-oriented programming language, therefore, it comprises objects. All objects have
methods and properties, and they can are differentiated and connected by the hierarchy. For
the ListBox, Item is an object subordinated to the object ListBox. Item comprises a method called
ListBox.Items.Add("Text")
You can enable the user to add their own items via an InputBox function. To add this capability,
insert a Button at design time and change its text to Add Item. Click on the Button and enter
the following statements in the code window:
* The keyword Dim is to declare the variable myitem. You will learn more about Dim and
variables in coming lessons
Running the program and clicking on the Add item button will bring up an InputBox where the
user can key in the item he or she wants to add to the list, as shown in Figure 6.3
In Visual Basic 2019, the function of the ComboBox is also to present a list of items where
the user can click and select the items from the list. However, the user needs to click on the
handle(small arrowhead) on the right of the ComboBox to see the items which are presented in a
drop-down list.
In order to add items to the list at design time, you can also use the String Collection Editor. You
will have to type an item under the text property in order to display the default item at runtime.
The runtime interface is as shown in Figure 6.7
Besides, you may add items using the Add() method. The statement to add an item to the
ComBox is as follows:
ComboBox1.Items.Add
Entering the item "Visual Studio 2019" and clicking the OK button will show that the item has
been added to the list, as shown in Figure 6.10
If the user key in VB6, the item will be deleted from the ComboBox, as shown in Figure
6.12.
PictureBox is a control in Visual Basic 2019 that is used to display images.In lesson 3, we
have already learned how to insert a PictureBox on the form in Visual Basic 2019. However, we
have not learned how to load a picture in the PictureBox yet. In this lesson, we shall learn how to
load an image into the PictureBox at design time and at runtime. Besides that, we shall also learn
how to use a common dialog control to browse for image files in your local drives and then select
and load a particular image in the PictureBox.
First, insert a PictureBox on the form and change its text property to Picture Viewer, its border
property to FixedSingle and its background color to white. You might also want to change the size
mode of the image to stretchImage so that the image can fit in the PictureBox. Now right-click on
Next, click on the grey button on its right to bring out the “Select Source” dialog
Now select local source and click on the Import button to bring up the Open dialog and view the
available image files in your local drives.
In Visual Basic 2017, an image can also be loaded at runtime using the FromFile method
of the Image control, as shown in the following example.
* You need to search for an image on your local drive and determine its path before you write the
code.
Running the program will display the same image in the PictureBox as in Figure 7.4
We have learned how to load an image from a local drive into a PictureBox at design time.
Now we shall write code so that the user can browse for the image files in his or her local drives
then select a particular image and display it on the PictureBox at runtime.
First, we add a button and change its text to View and its name to BtnView. Next, we add
the OpenFileDialog control on the form. This control will be invisible during runtime but it
facilitates the process of launching a dialog box and let the user browse his or her local
drives and then select and open a file. In order for the OpenFileDialog to display all types of
image files, we need to specify the types of image files under the Filter property. Before that,
as shown in Figure 7.5. These are the common image file formats. Besides that, you also need to
delete the default Filename.
Press F5 to run the program and click the View button, a dialog box showing all the image files
will appear.
1 MenuStrip
It provides a menu system for a form.
2 ToolStripMenuItem
It represents a selectable option displayed on a MenuStrip or ContextMenuStrip. The
ToolStripMenuItem control replaces and adds functionality to the MenuItem control of previous
versions.
3 ContextMenuStrip
It represents a shortcut menu.
Anchoring allows you to set an anchor position for a control to the edges of its container control,
for example, the form. The Anchor property of the Control class allows you to set values of this
property. The Anchor property gets or sets the edges of the container to which a control is bound
and determines how a control is resized with its parent.
When you anchor a control to a form, the control maintains its distance from the edges of
the form and its anchored position, when the form is resized.
For example, let us add a Button control on a form and set its anchor property to Bottom,
Right. Run this form to see the original position of the Button control with respect to the form.
Now, when you stretch the form, the distance between the Button and the bottom right
corner of the form remains same.
For example, let us add a Button control on a form and set its Dock property to Bottom.
Run this form to see the original position of the Button control with respect to the form.
Modal Forms
Modal Forms are those forms that need to be closed or hidden before you can continue
working with the rest of the application. All dialog boxes are modal forms. A MessageBox is
also a modal form.
You can call a modal form by two ways −
Calling the ShowDialog method
Calling the Show method
Let us take up an example in which we will create a modal form, a dialog box. Take the
following steps −
Add a form, Form1 to your application, and add two labels and a button control to Form1
Change the text properties of the first label and the button to 'Welcome to Tutorials Point'
and 'Enter your Name', respectively. Keep the text properties of the second label as
blank.
Clicking on the 'Enter your Name' button displays the second form −
Clicking on the OK button takes the control and information back from the modal form to the
previous form −
Events are basically a user action like key press, clicks, mouse movements, etc., or
some occurrence like system generated notifications. Applications need to respond to events
when they occur.
Clicking on a button, or entering some text in a text box, or clicking on a menu item, all
are examples of events. An event is an action that calls a function or may cause another
event. Event handlers are functions that tell how to respond to an event.
VB.Net is an event-driven language. There are mainly two types of events −
Mouse events
Keyboard events
Mouse events occur with mouse movements in forms and controls. Following are the
various mouse events related with a Control class −
MouseDown − it occurs when a mouse button is pressed
MouseEnter − it occurs when the mouse pointer enters the control
MouseHover − it occurs when the mouse pointer hovers over the control
Example
Following is an example, which shows how to handle mouse events. Take the following steps −
Add three labels, three text boxes and a button control in the form.
Change the text properties of the labels to - Customer ID, Name and Address,
respectively.
Change the name properties of the text boxes to txtID, txtName and txtAddress,
respectively.
Change the text property of the button to 'Submit'.
Add the following code in the code editor window −
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
Following are the various keyboard events related with a Control class −
KeyDown − occurs when a key is pressed down and the control has focus
KeyPress − occurs when a key is pressed and the control has focus
KeyUp − occurs when a key is released while the control has focus
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties −
Alt − it indicates whether the ALT key is pressed
Control − it indicates whether the CTRL key is pressed
Example
Let us continue with the previous example to show how to handle keyboard events. The code will
verify that the user enters some numbers for his customer ID and age.
Add a label with text Property as 'Age' and add a corresponding text box named txtAge.
Add the following codes for handling the KeyUP events of the text box txtID.
Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtID.KeyUp
(Source: VB. Net Event Handling. (2020, November 30). Retrieved from
https://www.tutorialspoint.com/vb.net/vb.net_event_handling.htm)
Supplemental Readings/Assignments
1. http://vb.net-informations.com/
2. https://www.homeandlearn.co.uk/NET/vbNet.html
3. https://www.tutorialspoint.com/vb.net/index.htm
V. Assessment Tasks
Diagnostic Assessment
Direction : The first quiz includes simple hands-on activity on the application of VB.Net
Exception and File Handling.
In order for the student to create and execute the source code for the hands-on
activity, he/she should have installed Microsoft Visual Studio in the laptop or desktop of
which the installer is provided by the instructor.
End If
End Sub
End Class
Sub Main()
Dim obj As Divide = New Divide()
Try
obj.showNumber()
Catch ex As EvenorOddNo
Console.WriteLine("EvenorOddNo: {0}", ex.Message)
End Try
Console.ReadKey()
End Sub
End Module
Direction: This hands-on activity serves as assessment for students on their level of
analysis by developing simple program using VB.Net Basic Controls.
In order for the student to create and execute the source code for the hands-on
activity on Part II of the quiz, he/she should have installed Microsoft Visual Studio in
his/her laptop or desktop of which the installer is provided by the instructor. Softcopy of
the student’s answers on quizzes/activities should be sent in the instructor’s email address.
In case the student has no available laptop or desktop where the program will be
created, he/she may write the source code in a yellow paper and submit to the instructor in
any means as long as the answers will be received by the instructor.
Machine Problem: Write one(1) program using Textbox that shows Password
Encryption
MsgBox("Successful login")
Else
End Sub
End Class
Direction: The hands-on activity deals with VB.Net Menu. This serves as quiz
number 4 , in here the student will simply create a program that shows how various control
statements are utilized.
In order for the student to create and execute the source code for the hands-on
activity on Part II of the quiz, he/she should have installed Microsoft Visual Studio in
his/her laptop or desktop of which the installer is provided by the instructor. Softcopy of
the student’s answers on quizzes/activities should be sent in the instructor’s email address.
Machine Problem: Write one(1) sample program showing sample Menu and
Submenus in VB. Net
Sample Output:
mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)
mnuBar.MenuItems.Add(myMenuItemHelp)
myMenuItemFile.MenuItems.Add(myMenuItemCreateNewFile)
myMenuItemFile.MenuItems.Add(myMenuItemOpenFile)
myMenuItemFile.MenuItems.Add(myMenuItemSaveFile)
Me.Menu = mnuBar
End Sub
End Class
Appendix A
Description 0 1 2 3
Use appropriate
variable name
1 YES 2 YES
Use appropriate
No and 2 and 1 YES
variable type
NO NO
Use appropriate
control structure
Description 0 1 2
Follows the
1 YES
naming convention
No and 1 YES
Follows indention
NO
rule
Description 0 1 2 3
Follows appropriate No 1 2 YES YES
coding or YES and 1
guidelines / template and NO
Use appropriate 2
control structure / NO
desired method
Apply the techniques
INSTRUCTOR INFORMATION