0% found this document useful (0 votes)
70 views50 pages

Final Jimjim Oop - Learning Module - Final

This document is a course pack for Module 4 of CS 212 Object Oriented Programming at Surigao del Sur State University. It covers weeks 16-18 and includes topics on VB.Net exception handling, file handling, basic controls, advanced forms, and event handling. The module provides intended learning outcomes, general instructions, an introduction, and content for each week. It directs students to focus on assigned tasks and includes links to video tutorials to help students better understand the course content. Academic integrity policies are also outlined, requiring students to complete all assessments and not engage in plagiarism.

Uploaded by

JimJim Pajenado
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
70 views50 pages

Final Jimjim Oop - Learning Module - Final

This document is a course pack for Module 4 of CS 212 Object Oriented Programming at Surigao del Sur State University. It covers weeks 16-18 and includes topics on VB.Net exception handling, file handling, basic controls, advanced forms, and event handling. The module provides intended learning outcomes, general instructions, an introduction, and content for each week. It directs students to focus on assigned tasks and includes links to video tutorials to help students better understand the course content. Academic integrity policies are also outlined, requiring students to complete all assessments and not engage in plagiarism.

Uploaded by

JimJim Pajenado
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

Republic of the Philippines

Surigao del Sur State University


Rosario, Tandag City, Surigao del Sur 8300
Telefax No. 086-214-4221
www.sdssu.edu.ph

MODULE FOUR

A Course Pack in CS 212


Object Oriented Programming

BORN CHRISTIAN A. ISIP


ASSOCIATE PROFESSOR IV

November 2021

JimCarlo S. Pajenado 2CSA

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.

VB.Net Video Tutorials

Task/Topic Link Alloted Time


Basic Error Handling 12 minutes and
with Try Catch 13 seconds
Visual Basic 9 minutes and 22
Controls and Posted in Google Classroom
Properties seconds
Visual Basic Modern 24 minutes and
Forms 16 seconds

III. Academic Integrity

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

Four(4) topics are included in this module.

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

2|Page CS 212 OBJECT ORIENTED PROGRAMMING


VB.Net Advanced Form and Event Handling for weeks 17-18 with details of the given examples
to better understand the lessons.

Video Tutorials are also available for the learners to review and better understand the
course content included in Module 4.
WEEK 16

 Lesson 1: Exception and File Handling

Intended Learning Outcomes

After the lesson, students are expected to:

 Understand and discuss when it is appropriate to apply or use VB.Net Exception Handling
 Compile and execute sample code for Error File Handling

VB.NET Exception 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

where the problem arises.

Finally It is used to execute a set of statements in a program, whether an exception has occurred.

3|Page CS 212 OBJECT ORIENTED PROGRAMMING


Throw As the name suggests, a throw handler is used to throw an exception after the occurrence of a

problem.

An exception can occur due to different reasons, including the following:

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.

Exception Classes in VB.NET

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.

System.ApplicationException: It is an exception class that throws an exception defined within


the application by the programmer or developer. Furthermore, we can say that it is a user-defined
exception that inherits from System.ApplicationException class.

Syntax of exception handler block

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  

4|Page CS 212 OBJECT ORIENTED PROGRAMMING


9.     [ Finally Statements ] ]  
10. End Try  

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.

Example to Exception Handle

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:

5|Page CS 212 OBJECT ORIENTED PROGRAMMING


Using Try-Catch Statement

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:

6|Page CS 212 OBJECT ORIENTED PROGRAMMING


Throwing Objects

In VB.NET exception handling, we can throw an object exception directly or indirectly


derived from the System.Exception class. To throw an object using the throw statement in a catch
block, such as:

1. Throw [ expression ]  

Let's create a program to throw an object in VB.NET exception.

7|Page CS 212 OBJECT ORIENTED PROGRAMMING


throwexcept.vb

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:

Introduction to Error Handling

Error handling is an essential procedure in Visual Basic 2019 programming. Error-


free code not only enables the program to run smoothly and efficiently, but it can also
prevent all sorts of problems from happening like program crashes or system hangs. Errors
often occur due to incorrect input from the user. For example, the user might make the mistake of
attempting to enter text (string) to a box that is designed to handle only numeric values such as the
weight of a person, the computer will not be able to perform the arithmetic calculation for text,
therefore, will create an error. These errors are known as synchronous errors.

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

8|Page CS 212 OBJECT ORIENTED PROGRAMMING


2019 will not return an error message but gives the ‘infinity’ as the answer (although this is
mathematically incorrect because it should be undefined)

Using On Error GoTo Syntax

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

On Error GoTo program_label

where program_label is the section of code that is designed by the programmer to


handle the error committed by the user. Once an error is detected, the program will jump to
the program_label section for error handling.

Example : The Division Error

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

Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click


Lbl_ErrMsg.Visible = False
Dim firstNum, secondNum As Double

On Error GoTo error_handler


firstNum = val(TxtNum1.Text)
secondNum =val( TxtNum2.Text)
Lbl_Answer.Text = firstNum / secondNum

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

The runtime interface

9|Page CS 212 OBJECT ORIENTED PROGRAMMING


*Please Note that division by zero in Visual Basic 2015 no longer gives an error message, but
it displays the answer as Infinity.

Errors Handling using Try…..Catch….End Try Structure

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.

The structure looks like this

Try

statements

Catch exception_variable as Exception

statements to deal with exceptions

End Try
The Code

Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click


Lbl_ErrMsg.Visible = False
Dim firstNum, secondNum, answer As Double

Try

firstNum = TxtNum1.Text
secondNum = TxtNum2.Text
answer = firstNum / secondNum

10 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Lbl_Answer.Text = answer

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

The runtime interface

(Source: VB.NET Exception Handling. (2020, December 12). Retrieved from


https://www.javatpoint.com/vb-net-exception-handling)

Weeks 17-18

Lesson 2: Basic Controls


Intended Learning Outcomes

After the lesson, students are expected to:

 Understand and able to apply the importance of VB.Net Controls


 Build simple programs utilizing the different VB.Net Controls

11 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Working with Controls

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.

Figure 5.1: Visual Basic 2019 Controls

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,

12 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


PictureBox, timer and more. However, we shall only deal with the text box and the label in
this lesson. The text box is for accepting input from the user as well as to display the output. It
can handle string and numeric data but not images or pictures. String in a text box can be
converted to a numeric data by using the function Val(text). The label control is only for
displaying a caption/title or to display an output.

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:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

MsgBox("The sum is "& Val(TextBox1.Text) + Val(TextBox2.Text))

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.

13 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Writing Code for ListBox & ComboBox

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.

14 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Adding Items to a ListBox

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

15 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Add() that is used to add items to the ListBox. To add an item to a ListBox, you can use the
following syntax:

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:

Private Sub BtnAdd_Click(sender As Object, e As EventArgs) Handles Button1.Click


Dim myitem
myitem = InputBox("Enter your Item")
ListBox1.Items.Add(myitem)
End Sub

* 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

16 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


To clear all the items at once, use the clear method, as illustrated in the following
example. In this example, add a button and label it "Clear Items"

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button2.Click


ListBox1.Items.Clear()
End Sub
 ComboBox

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.

Adding Items to a ComboBox

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

17 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


After clicking the handle of the right side of the ComBox, the user will be able to view all the
items

Besides, you may add items using the Add() method. The statement to add an item to the
ComBox is as follows:

ComboBox1.Items.Add

18 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


In this program, we add a Button and name it as BtnAdd and change its text to Add
Item.Besides that, rename ComboBox1 as MyCombo. Enter the following

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.

19 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


To clear all the items at once, use the clear method, as illustrated in the following example. In this
example, add a button and label it "Clear All Items" and name it as Btn_Clr. Enter the following
Code:

Private Sub Btn_Clr_Click(sender As Object, e As EventArgs) Handles Button2.Click


MyCombo.Items.Clear()
End Sub

Working with PictureBox

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.

Loading an Image in the PictureBox

Loading an Image at Design Time

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

20 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


the PictureBox to bring out its properties window. In the Properties window, scroll to the
Image property.

PictureBox Properties window

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.

21 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Finally, select the image you like and then click the open button, the image will be
displayed in the PictureBox.

22 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Loading an Image at Runtime

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.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load


MyPicBox.Image = Image.FromFile("C:\Users\Public\Pictures\Sample Pictures\ Tulips.jpg ")
End Sub

* 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

Loading an Image in a PictureBox using Open File Dialog Control

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,

23 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


rename OpenFileDialog1 as OFGSelectImage. Next, right-click on the OpenFileDialog control to
access its properties window. Beside the Filter property, specify the image files using the format:

JPG Files| *.JPG|GIF Files|*.GIF|WIndows Bitmaps|*.BMP| JPEG Files|*.jpeg

as shown in Figure 7.5. These are the common image file formats. Besides that, you also need to
delete the default Filename.

Properties Window of OpenFileDialog

Next, double-click on the View button and enter the following code:

Private Sub BtnView_Click(sender As Object, e As EventArgs) Handles Button1.Click


If OpenFileDialog1.ShowDialog = DialogResult.OK Then
MyPicBox.Image = Image.FromFile(OFGSelectImage.FileName)
End If
End Sub

Press F5 to run the program and click the View button, a dialog box showing all the image files
will appear.

24 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Please notice that that the default image file is JPEG  as we have placed it in the first place in the
Filter property. Selecting and opening an image file will load it in the PictureBox.

25 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


(Source: Working with Controls. (2020, December 12). Retrieved from
https://www.vbtutor.net/vb2019/vb2019_lesson5.html)
________________________________________________________________________
 Lesson 3: Advanced Form

Intended Learning Outcomes

After the lesson, students are expected to:

 Identify and translate how VB.Net Forms works


 Make use of the VB.Net Forms in creating Menus, Sub Menus and other Functionalities of a
Form

In this topic, let us study the following concepts −


 Adding menus and sub menus in an application
 Anchoring and docking controls in a form
 Modal forms

Adding Menus and Sub Menus in an Application

26 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Traditionally, the Menu, MainMenu, ContextMenu, and MenuItem classes were used for adding
menus, sub-menus and context menus in a Windows application.
Let us create a typical windows main menu bar and sub menus using the old version controls first
since these controls are still much used in old applications.
Following is an example, which shows how we create a menu bar with menu items: File, Edit,
View and Project. The File menu has the sub menus New, Open and Save.
Let's double click on the Form and put the following code in the opened window.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'defining the main menu bar
Dim mnuBar As New MainMenu()
'defining the menu items for the main menu bar
Dim myMenuItemFile As New MenuItem("&File")
Dim myMenuItemEdit As New MenuItem("&Edit")
Dim myMenuItemView As New MenuItem("&View")
Dim myMenuItemProject As New MenuItem("&Project")

'adding the menu items to the main menu bar


mnuBar.MenuItems.Add(myMenuItemFile)
mnuBar.MenuItems.Add(myMenuItemEdit)
mnuBar.MenuItems.Add(myMenuItemView)
mnuBar.MenuItems.Add(myMenuItemProject)

' defining some sub menus


Dim myMenuItemNew As New MenuItem("&New")
Dim myMenuItemOpen As New MenuItem("&Open")
Dim myMenuItemSave As New MenuItem("&Save")

'add sub menus to the File menu


myMenuItemFile.MenuItems.Add(myMenuItemNew)
myMenuItemFile.MenuItems.Add(myMenuItemOpen)
myMenuItemFile.MenuItems.Add(myMenuItemSave)

'add the main menu to the form


Me.Menu = mnuBar

' Set the caption bar text of the form.


Me.Text = "tutorialspoint.com"
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

27 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Windows Forms contain a rich set of classes for creating your own custom menus with
modern appearance, look and feel.
The MenuStrip, ToolStripMenuItem, ContextMenuStrip controls are used to create menu
bars and context menus efficiently.
Click the following links to check their details −

Sr.No. Control & Description

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 and Docking Controls in a Form

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.

28 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


You can set the Anchor property values of a control from the Properties window −

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.

29 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Docking of a control means docking it to one of the edges of its container. In docking, the
control fills certain area of the container completely.
The Dock property of the Control class does this. The Dock property gets or sets which
control borders are docked to its parent control and determines how a control is resized
with its parent.
You can set the Dock property values of a control from the Properties window −

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.

30 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Now, when you stretch the form, the Button resizes itself with 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.

31 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


 Add a new Windows Form, Form2, and add two buttons, one label, and a text box to
Form2.
 Change the text properties of the buttons to OK and Cancel, respectively. Change the text
properties of the label to 'Enter your name:'.
 Set the FormBorderStyle property of Form2 to FixedDialog, for giving it a dialog box
border.
 Set the ControlBox property of Form2 to False.
 Set the ShowInTaskbar property of Form2 to False.
 Set the DialogResult property of the OK button to OK and the Cancel button to
Cancel.

Add the following code snippets in the Form2_Load method of Form2 −


Private Sub Form2_Load(sender As Object, e As EventArgs) _
Handles MyBase.Load
AcceptButton = Button1
CancelButton = Button2
End Sub
Add the following code snippets in the Button1_Click method of Form1 −

32 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Private Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
Dim frmSecond As Form2 = New Form2()

If frmSecond.ShowDialog() = DialogResult.OK Then


Label2.Text = frmSecond.TextBox1.Text
End If
End Sub
When the above code is executed and run using Start  button available at the Microsoft Visual
Studio tool bar, it will show the following window −

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 −

33 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


(Source: VB.NET Advanced Form. (2020, December 12). Retrieved from
https://www.tutorialspoint.com/vb.net/vb.net_advanced_forms.htm)

 Lesson 4: Event Handling

Intended Learning Outcomes

After the lesson, students are expected to:

 Outline and evaluate the appropriate VB.Net Event Handling


 Make use of VB.Net Events by illustrating an example.

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

Handling Mouse 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

34 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


 MouseLeave − it occurs when the mouse pointer leaves the control
 MouseMove − it occurs when the mouse pointer moves over the control
 MouseUp − it occurs when the mouse pointer is over the control and the mouse button is
released
 MouseWheel − it occurs when the mouse wheel moves and the control has focus
The event handlers of the mouse events get an argument of type MouseEventArgs. The
MouseEventArgs object is used for handling mouse events. It has the following properties −
 Buttons − indicates the mouse button pressed
 Clicks − indicates the number of clicks
 Delta − indicates the number of detents the mouse wheel rotated
 X − indicates the x-coordinate of mouse click
 Y − indicates the y-coordinate of mouse click

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

Private Sub txtID_MouseEnter(sender As Object, e As EventArgs)_


Handles txtID.MouseEnter
'code for handling mouse enter on ID textbox
txtID.BackColor = Color.CornflowerBlue
txtID.ForeColor = Color.White
End Sub

Private Sub txtID_MouseLeave(sender As Object, e As EventArgs) _


Handles txtID.MouseLeave
'code for handling mouse leave on ID textbox
txtID.BackColor = Color.White
txtID.ForeColor = Color.Blue
End Sub

35 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Private Sub txtName_MouseEnter(sender As Object, e As EventArgs) _
Handles txtName.MouseEnter
'code for handling mouse enter on Name textbox
txtName.BackColor = Color.CornflowerBlue
txtName.ForeColor = Color.White
End Sub

Private Sub txtName_MouseLeave(sender As Object, e As EventArgs) _


Handles txtName.MouseLeave
'code for handling mouse leave on Name textbox
txtName.BackColor = Color.White
txtName.ForeColor = Color.Blue
End Sub

Private Sub txtAddress_MouseEnter(sender As Object, e As EventArgs) _


Handles txtAddress.MouseEnter
'code for handling mouse enter on Address textbox
txtAddress.BackColor = Color.CornflowerBlue
txtAddress.ForeColor = Color.White
End Sub

Private Sub txtAddress_MouseLeave(sender As Object, e As EventArgs) _


Handles txtAddress.MouseLeave
'code for handling mouse leave on Address textbox
txtAddress.BackColor = Color.White
txtAddress.ForeColor = Color.Blue
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) _


Handles Button1.Click
MsgBox("Thank you " & txtName.Text & ", for your kind cooperation")
End Sub
End Class
When the above code is executed and run using Start button available at the Microsoft
Visual Studio tool bar, it will show the following window :

36 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Try to enter text in the text boxes and check the mouse events −

Handling Keyboard Events

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

37 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


 Handled − it indicates whether the event is handled
 KeyCode − stores the keyboard code for the event
 KeyData − stores the keyboard data for the event
 KeyValue − stores the keyboard value for the event
 Modifiers − it indicates which modifier keys (Ctrl, Shift, and/or Alt) are pressed
 Shift − it indicates if the Shift key is pressed
The event handlers of the KeyDown and KeyUp events get an argument of type KeyEventArgs.
This object has the following properties −
 Handled − indicates if the KeyPress event is handled
 KeyChar − stores the character corresponding to the key 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

If Not Isnumeric(txtID.text) Then


MessageBox.Show("Enter numbers for your Customer ID")
txtID.Text = " "
End If
End Sub
 Add the following codes for handling the KeyUP events of the text box txtID.
Private Sub txtAge_KeyUP(sender As Object, e As KeyEventArgs) _
Handles txtAge.KeyUp

If Not Isnumeric(txtAge.text) Then


MessageBox.Show("Enter numbers for age")
txtAge.Text = " "
End If
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, it will show the following window −

38 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


If you leave the text for age or ID as blank or enter some non-numeric data, it gives a warning
message box and clears the respective text −

(Source: VB. Net Event Handling. (2020, November 30). Retrieved from
https://www.tutorialspoint.com/vb.net/vb.net_event_handling.htm)

Supplemental Readings/Assignments

“Visual Basic.NET. Retrieved from https://www.homeandlearn.co.uk/NET/vbNet.html”

Other print materials (if any)

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

39 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


LESSON 1 -Quiz #1:Total points (30)

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.

Write one(1) sample program for each of the following

A. Divided By Zero Exception


Sample output:
'Jimcarlo Pajenado 2CSA
Module Module1
Sub division(ByVal n1 As Integer, ByVal n2 As Integer)
Dim res As Integer
Try
res = n1 \ n2
Catch ex As DivideByZeroException
Console.WriteLine("Exception caught: {0}", ex)
Finally
Console.WriteLine("Result: {0}", res)
End Try
End Sub
Sub Main()
division(100, 0)
Console.ReadKey()
End Sub
End Module

40 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


41 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING
B. Customized Exceptions that is if the number is divided by 2 if the result is 0
then it is an even number else if the result is not 0 it is an odd number.
Sample Output:
'Jimcarlo Pajenado
Module Module1
Public Class EvenorOddNo : Inherits ApplicationException
Public Sub New(ByVal message As String)
MyBase.New(message)
End Sub
End Class
Public Class Divide
Dim AnyNo As Integer = 55
Dim No As Integer = 2
Sub showNumber()
If (AnyNo Mod No > 0) Then
Throw (New EvenorOddNo("The number is an odd number"))
Else
Console.WriteLine("The number is an even number : {0}", AnyNo)

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

42 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


43 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING
LESSON 2-Quiz #2 Hands-on Quiz: Total points (30)

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.

Scores of every student on quizzes/activities will be posted in the google classroom


created for course OOP.

Machine Problem: Write one(1) program using Textbox that shows Password
Encryption

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles BtnLogin.Click

If TxtUsername.Text = "JimjimPajenado" And TxtPassword.Text = "12345" Then

MsgBox("Successful login")

Else

MsgBox("Please try again")

44 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


End If

End Sub

End Class

LESSON 3-Quiz #3 Hands-on Quiz: Total points (40)

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.

45 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


In case the student have 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.

Scores of every student on quizzes/activities will be posted in the google classroom


created for course OOP.

Machine Problem: Write one(1) sample program showing sample Menu and
Submenus in VB. Net

Sample Output:

Public Class Form1

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles


MyBase.Load

'defining the main menu bar

Dim mnuBar As New MainMenu()

'defining the menu items for the main menu bar

Dim myMenuItemFile As New MenuItem("&File")

Dim myMenuItemEdit As New MenuItem("&Edit")

Dim myMenuItemView As New MenuItem("&View")

Dim myMenuItemProject As New MenuItem("&Project")

Dim myMenuItemProject As New MenuItem("&Debug")

Dim myMenuItemProject As New MenuItem("&Help")

'adding the menu items to the main menu bar

mnuBar.MenuItems.Add(myMenuItemFile)

mnuBar.MenuItems.Add(myMenuItemEdit)

mnuBar.MenuItems.Add(myMenuItemView)

mnuBar.MenuItems.Add(myMenuItemProject)

46 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


mnuBar.MenuItems.Add(myMenuItemDebug)

mnuBar.MenuItems.Add(myMenuItemHelp)

' defining some sub menus

Dim myMenuItemNew As New MenuItem("&CreateNewFile")

Dim myMenuItemOpen As New MenuItem("&OpenFile")

Dim myMenuItemSave As New MenuItem("&SaveFile")

'add sub menus to the File menu

myMenuItemFile.MenuItems.Add(myMenuItemCreateNewFile)

myMenuItemFile.MenuItems.Add(myMenuItemOpenFile)

myMenuItemFile.MenuItems.Add(myMenuItemSaveFile)

'add the main menu to the form

Me.Menu = mnuBar

' Set the caption bar text of the form.

Me.Text = "Jimjim Menu's bar "

End Sub

End Class

47 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


VI. References

48 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


Online

1. VB.NET Exception Handling. (2020, December 12). Retrieved from


https://www.javatpoint.com/vb-net-exception-handling
2. Working with Controls. (2020, December 12). Retrieved from
https://www.vbtutor.net/vb2019/vb2019_lesson5.html
3. VB.NET Advanced Form. (2020, December 12). Retrieved from
https://www.tutorialspoint.com/vb.net/vb.net_advanced_forms.htm
4. VB. Net Event Handling. (2020, November 30). Retrieved from
https://www.tutorialspoint.com/vb.net/vb.net_event_handling.htm

Appendix A

Rubric for Script / Program

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

Rubric for Coding Style

Description 0 1 2
Follows the
1 YES
naming convention
No and 1 YES
Follows indention
NO
rule

Rubric for Project

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

49 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING


of decomposition to
break a program into
smaller pieces or
follows the required
technique

INSTRUCTOR INFORMATION

Name : Born Christian A. Isip


Email Address : [email protected]
Contact Number : 09218722418
Consultation Hours : Monday 8:00 am – 12:00 nn

Mode of Teaching/Learning Delivery : Flexible


Tools/Platforms : Google Classroom
BlackBoard LMS
Google Meet Link: https://meet.google.com/yaq-xagp-hwz

50 | P a g e CS 212 OBJECT ORIENTED PROGRAMMING

You might also like