Bca VBP
Bca VBP
Bca VBP
CLS: The CLS is simply a specification that defines the rules to support language integration in
such a way that programs written in any language. Yet can interoperate with one another, taking
full advantage of inheritance, polymorphism, exceptions, and other features.
CTS: Common Type System (CTS) describes how types are declared, used and managed in the
runtime and facilitates cross-language integration, type safety, and high performance code
execution. CLR: The .NET Framework provides a runtime environment called the Common
Language Runtime or CLR (similar to the Java Virtual Machine or JVM in Java), which handles
the execution of code and provides useful services for the implementation of the program.
CLR takes care of code management at program execution and provides various beneficial
services such as memory management, thread management, security management, code
verification, compilation, and other system services.
CLR benefits from useful features such as cross-language integration, cross-language exception
handling, versioning, enhanced security, deployment support, and debugging.
CLR is a Runtime Engine with collection of services as follows.
1. Assembly Resolver: It will read the manifest of the application. It will identify private
assemblies and shared assemblies required for application. It will forward request to
Assembly Loader.
2. Assembly Loader: It will load the assemblies from its location.
3. Type Checker: It will verify all the types used in applications with CTS or CLS, Level
standards. This provides type safety.
4. Debug Manager: It will support line by line execution to identify logical errors.
5. Exception Handler: It will handles Exceptions in the application using Try and Catch
blocks. If there is no catch block for exception it will terminate the application.
6. Garbage Collector: It will releases memory of unused objects. This provides automatic
memory management.
7. COM Marshaller: It will provide communication with COM component. This will
support interoperability with COM.
8. Thread Support: It will manage more than one execution path with in application process.
This will support Multi Threading.
9. JIT Compiler: JIT stands for Just-In-Time. It will converts Intermediate Language into
Native Code.
DOTNET Framework version history
2012
4.5
Store/UWP apps Model
2010
4.0
Library
2007
3.5
LINQ Entity Framework
2006
WF
3.0
Space
WinForms ASP.NET
2005
Framework Class Library
ASP.NET Features
• Support for new HTML5 form types.
• Support for model binders in Web Forms. These let you bind data controls directly to
dataaccess methods, and automatically convert user input to and from .NET Framework
data types.
• Support for unobtrusive JavaScript in client-side validation scripts.
• Support for WebSocket protocol.
• Support for reading and writing HTTP requests and responses asynchronously.
• Support for asynchronous modules and handlers.
The namespace keyword is used to declare a scope. This namespace scope lets you
organize code and gives you a way to create globally-unique types. Even if you do not explicitly
declare one, a default namespace is created. This unnamed namespace, sometimes called the
global namespace, is present in every file. Any identifier in the global namespace is available for
use in a named namespace. Namespaces implicitly have public access and this is not modifiable.
Different NameSpaces used in DotNet are
System.Object.
System.IO.
System.Data.OLEDB
System.Threading
System.Rintime.Remoting.
Menu Description
File Contains commands for opening, closing, adding and saving projects,
as well as printing project data and exiting Visual Studio.
Edit Contains commands for editing programs, such as cut, copy, paste,
undo, redo, delete, find and select.
View Contains commands for displaying windows (e.g., Solution Explorer,
Toolbox, Properties window) and for adding toolbars to the IDE.
Project Contains commands for managing projects and their files.
Build Contains commands for compiling a program.
Debug Contains commands for debugging (i.e., identifying and correcting
problems in a program) and running a program. Debugging is
discussed in detail in Appendix C.
Data Contains commands for interacting with databases (i.e., organized
collections of data stored on computers), which we discuss in
Chapter 20, Database, SQL and ADO.NET).
Format Contains commands for arranging and modifying a form's controls.
Note that the Format menu appears only when a GUI component is
selected in Design view.
Tools Contains commands for accessing additional IDE tools (e.g., the
Toolbox) and options that enable you to customize the IDE.
Window Contains commands for arranging and displaying windows.
Community Contains commands for sending questions directly to Microsoft,
checking question status, sending feedback on Visual C# and searching
the CodeZone developer center and the Microsoft developers
community site.
Help Contains commands for accessing the IDE's help features.
VB.NET Features
• VB.NET is not case sensitive like other languages such as C++ and Java.
• It is an object-oriented programming language. It treats everything as an object.
• Automatic code formatting, XML designer, improved object browser etc.
• Garbage collection is automated.
• Support for Boolean conditions for decision making.
• Simple multithreading, allowing your apps to deal with multiple tasks simultaneously.
Simple generics.
• A standard library.
• Events management.
• References. You should reference an external object that is to be used in a VB.NET
application.
• Attributes, which are tags for providing additional information regarding elements that
have been defined within a program.
• Windows Forms- you can inherit your form from an already existing form.
Advantages of VB.NET
The following are the benefits of VB.NET:
• Your code will be formatted automatically.
• You will use object-oriented constructs to create an enterprise-class code.
• You can create web applications with modern features like performance counters, event
logs, and file system.
• You can create your web forms with much ease through the visual forms designer. You
will also enjoy drag and drop capability to replace any elements that you may need.
• You can connect your applications to other applications created in languages that run on
the .NET framework.
• You will enjoy features like docking, automatic control anchoring, and in-place menu
editor all good for developing web applications.
Disadvantages of VB.NET
Below are some of the drawbacks in VB.NET:
• VB.NET cannot handle pointers directly. This is a significant disadvantage since pointers
are much necessary for programming. Any additional coding will lead to many CPU
cycles, requiring more processing time. Your application will become slow.
• VB.NET is easy to learn. This has led to a large talent pool. Hence, it may be challenging
to secure a job as a VB.NET programmer.
Arithmetic Operators
The Arithmetic Operators in VB.NET, used to perform mathematical operations such as
subtraction, addition, multiplication, division, etc. on the operands in VB.NET. These are as
follows:
Logical Operators
The logical and bitwise Operators work with Boolean (true or false) conditions, and if the
conditions become true, it returns a Boolean value. The following are the logical Operators used
to perform the various logical operations such as And, Or, Not on the operands. Suppose there
are two operand A and B, where A is True, and B is False.
Assignment Operators
The Assignment Operators are used to assign the value to variables in VB.NET.
Concatenation Operators
In VB.NET, there are two concatenation Operators to bind the operands:
Algorithms:
Any computing problem can be solved by executing a series of actions in a specific order.
A procedure for solving a problem, in terms of the actions to be executed and the order in
which these actions are to be executed is called an algorithm.
Pseudocode:
Pseudocode is an informal language that helps you develop algorithms. It's similar to
everyday English; it's convenient and user friendly, but not an actual computer programming
language. The pseudocode we present is particularly useful for developing algorithms that will be
converted to structured portions of Visual Basic programs.
Control Structures:
In VB.NET, the control statements are the statements that controls the execution of the
program on the basis of the specified condition. It is useful for determining whether a condition
is true or not. If the condition is true, a single or block of statement is executed. In the control
statement, we will use if- Then, if Then Else, if Then ElseIf and the Select case statement. We
can define more than one condition to be evaluated by the program with statements. If the
defined condition is true, the statement or block executes according to the condition, and if the
condition is false, another statement is executed.
In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and
the statement can be single or group of statements that will be executed when the condition is
true.
Example 2: Write a program to print a number is greater than another number in VB.NET.
if_statment2.vb
Module if_statement2
Sub Main()
?Definition of variables
Dim no1, no2 As Integer
Console.WriteLine("Enter any two number:")
no1 = Console.ReadLine() ?read no1 from user
no2 = Console.ReadLine() ?read no2 from user
If no1 > no2 Then
Console.WriteLine("First number is greater than second number")
End If
If no1 < no2 Then
Console.WriteLine("Second number is greater than First number")
End If
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button
In the above program, we enter two numbers to find the greater number using the relational
operator. And if the first number is greater than the other, the first statement is executed;
otherwise, the second statement will be executed.
If-Then-Else Statement
The If-Then Statement can execute single or multiple statements when the condition is
true, but when the expression evaluates to false, it does nothing. So, here comes the If-Then-Else
Statement. The IF-Then-Else Statement is telling what If condition to do when if the statement is
false, it executes the Else statement. Following is the If-Then-Else statement syntax in VB.NET
as follows:
Syntax:
If (Boolean_expression) Then
'This statement will execute if the Boolean condition is true
Else
'Optional statement will execute if the Boolean condition is false
End If
The above diagram represents that if the Boolean expression (condition) is true, the if
statement will execute, and if the Boolean expression is false, Else code or statement will be
executed. After that, the control transfer to the next statement, which is immediately after the If-
Then-Else control statement.
Example 2: Write a program to print the larger and smaller of the two numbers.
if_else_statment2.vb
Module if_else_statement2
Sub Main()
Dim a As Integer
Dim b As Integer
Console.WriteLine("Enter the first number : ")
a = Console.ReadLine()
Console.WriteLine("Enter the second number : ")
b = Console.ReadLine()
If a > b Then
Console.WriteLine(" larger number = {0} and smaller number = {1} ", a,
b)
Else
Console.WriteLine(" larger number = {0} and smaller number = {1} ", b, a)
End If
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button.
If this condition is true in the if-else-if statement, the statement is executed within the if
block. If the condition is not true, it passes control to the next ElseIf condition to check whether
the condition is matched. And if none of the conditions are matched, the else block is executed.
Example 2: Write a program to use the If-Then-ElseIf Statement for calculating the division
obtained by the student. Also, take the marks obtained by the student in 5 different subjects from
the keyboard.
if_elseIf2.vb
Module If_elseIf2
Sub Main() ' execution start from Main() method
Dim m1, m2, m3, m4, m5, per As Integer
Console.WriteLine("Enter marks in five subjects ")
' Read the marks of five
subject m1 =
Console.ReadLine() m2 =
Console.ReadLine() m3 =
Console.ReadLine() m4 =
Console.ReadLine() m5 =
Console.ReadLine()
per = (m1 + m2 + m3 + m4 + m5) / 5
If (per >= 70) Then
'if condition is true, print the first division
Console.WriteLine(" First division")
ElseIf (per >= 60) Then
'if ElseIf condition is true, print the second division
Console.WriteLine(" Second division")
ElseIf (per >= 50) Then
'if ElseIf condition is true, print the third division
Console.WriteLine(" Third division")
ElseIf (per >= 40) Then
'if ElseIf condition is true, print only pass with grace
Console.WriteLine(" Only Pass with Grace")
Else
'if none of the condition is true, print the Failed
Console.WriteLine(" Failed")
End If
Console.WriteLine("press any key to exit...")
Console.ReadKey()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button.
Select Case Statement:
In VB.NET, the Select Case statement is a collection of multiple case statements, which
allows executing a single case statement from the list of statements. A selected case statement
uses a variable to test for equality against multiple cases or statements in a program. If the
variable is matched with any test cases, that statement will be executed. And if the condition is
not matched with any cases, it executes the default statement.
Using the select case statement in VB.NET programming, you can replace the uses of
multiple If-Then-Else If statement from the program for better readability and easy to use.
Syntax
Following is the syntax of the Select Case statement in VB.NET, as follows:
Select Case [variable or expression]
Case value1 'defines the item or value that you want to match.
Define a statement to execute
Case value2 'defines the item or value that you want to match.
Define a statement to execute
Case Else
Define the default statement if none of the conditions is true.
End Select
Furthermore, you can also set more than one condition in a single case statement, such as:
Select Case Variable / expression
Case value1
Statement1
Case value2, value3
Statement2
Case Else define the default statement if none of the
condition is true
End Select
In the Select Case statement represents the evaluating of the process start from top to
bottom. If the expression or value is matched with the first select case, statement -1 is executed
else the control transfer to the next case for checking whether the expression is matching or not.
Similarly, it checks all Select case statements for evaluating. If none of the cases are matched, the
Else block statement will be executed, and finally, the Select Case Statement will come to an
end.
Example 1: Write a program to display the Days name using the select case statement in
VB.NET.
Select_case.vb
Imports System
Module Select_case
Sub Main()
'define a local variable.
Dim Days As String
Days = "Thurs"
Select Case Days
Case "Mon"
Console.WriteLine(" Today is Monday")
Case "Tue"
Console.WriteLine(" Today is Tuesday")
Case "Wed"
Console.WriteLine("Today is Wednesday")
Case "Thurs"
Console.WriteLine("Today is Thursday")
Case "Fri"
Console.WriteLine("Today is Friday")
Case "Sat"
Console.WriteLine("Today is Saturday")
Case "Sun"
Console.WriteLine("Today is Sunday")
Case Else
Console.WriteLine(" You have typed Something wrong")
End Select
Console.WriteLine("You have selected : {0}", Days)
Console.WriteLine("Press any key to exit...")
Console.ReadLine()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:
In the select case statement, the value of Days "Thurs" will compare all the available
select cases' values in a program. If a value matched with any condition, it prints the particular
statement, and if the value is not matched with any select case statement, it prints the default
message. Example 2: Write a program to perform an arithmetic operation using the Select case
statement in VB.NET.
Imports System
Module Operation
Sub main()
'declaration of the variables
Dim num1, num2, sum As Integer
Dim def As Char
'initialization of num1 and num2
variable num1 = 2 num2 = 6
Console.WriteLine(" Want to perform any operation?")
Console.WriteLine(" A for Addition")
Console.WriteLine(" S for Subtraction")
Console.WriteLine(" M for Multiplication")
Console.WriteLine(" D for Division")
Console.WriteLine(" Please enter any input")
def = Console.ReadLine()
Select Case def
Case "A"
'perform Addition
sum = num1 + num2
Console.WriteLine(" Addition of two number is :{0}", sum)
Case "S"
'perform Subtraction
sum = num2 - num1
Console.WriteLine(" Subtraction of two number is :{0}", sum)
Case "M"
'perform Multiplication
sum = num1 * num2
Console.WriteLine(" Multiplication of two number is :{0}", sum)
Case "D"
'Peform Division
sum = num2 / num1
Console.WriteLine(" Division of two number is :{0}", sum)
Case Else
'If none of the operation matched, call default statement
Console.WriteLine(" Please enter only define operation With Capital letter")
End Select
Console.WriteLine("Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:
In the above example, we defined Select with multiple case statements, and if the user-defined
input is matched with any defined case statement, it executes that statement. And if the condition
is not matched with any case, it executes a default statement in VB.NET.
Here, we provide 'M' as input, which checks all case statements, and if any case is matched with
M, it executes the statement within the respective Case statement.
VB.NET Nested Select Case statements
When a Select Case statement is written inside the body of another Select Case statement is
called a nested Select Case statement.
Syntax:
Select Case "num"
' code to be executed if num = 1
Case 1
' nested Select case
Select Case n
' code to be executed if n = 5
Case 5
Statement 1
' code to be executed if n = 10
Case 10
Statement 2
' code to be executed if n = 15
Case 15
Statement 3
' code to be executed if n doesn't match with any cases.
Case Else
Statement
' code to be executed if num = 2
Case 2
Statement 2
' code to be executed if num = 3
Case 3
Statement 3
' code to be executed if num doesn't match with any cases.
Case Else
Statement
Now compile and execute the above program by clicking on the Start or F5 button Example 2:
Write a program to use the nested select case statement in VB.NET.
nested_selectcase.vb
Imports System
Module nested_selectcase
Sub Main()
Dim num As
Integer Dim str As
String str = "F"
Console.WriteLine(" Enter only First three number like 1, 2, 3")
num = Console.ReadLine() 'take input from the user
Select Case num
Case 1
Console.WriteLine(" You are in block 1")
Console.WriteLine("Only First two letter such as A and B")
str = Console.ReadLine()
Select Case str
Case "A", "a"
Console.WriteLine(" This is a VB.NET Tutorial")
Case "B", "b"
Console.WriteLine(" Welcome to the JavaTpoint")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case 2
Console.WriteLine(" You are in block 2")
Console.WriteLine("Only First two letter such as C and D")
str = Console.ReadLine()
Select Case str
Case "C", "c"
Console.WriteLine(" Welcome to the World!")
Case "D", "d"
Console.WriteLine(" Want to go in Heaven")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case 3
Console.WriteLine(" You are in block 3")
Console.WriteLine("Only First two letter such as E and F")
str = Console.ReadLine()
Select Case str
Case "E", "e"
Console.WriteLine(" VB.NET is a programming language to develop web,
windo w, and console-based application. ")
Case "F", "f"
Console.WriteLine(" You have to basic knowledge of c and c++")
Case Else
Console.WriteLine(" Something is wrong")
End Select
Case Else
Console.WriteLine(" Something is wrong")
End Select
Console.ReadLine()
End Sub
End Module
Now compile and execute the above program by clicking on the Start or F5 button, it shows the
following output:
In the above example, we have only defined the first three numbers 1-3 and if the number
matches to any case statement, the select statement is executed. Here, we have entered 2 that is
matched with case 2 and it executes a block as shown above. And this block executes the
statement "Only the First two letters such as C and D". Therefore, we enter a letter D, letter D is
matched with the nested select case statement, and if a match is found, it executes the select case
statement as shown above.
Debugging In VB.NET
Debugging is a process by which the errors in coding are set right. For this we need to
know the type of errors and when they occur.
Syntax Error:
These types of errors are triggered while compiling, when the code is not understandable
to the compiler. Usually this type of errors occurs due to bad syntax like wrong keywords,
programming structure mistakes.
Syntax errors in vb.net 2008 are highlighted using a line and also a tool tip appears specifying the
reason for the error, as the mouse is moved near the point where the error occurred. These errors
are also displayed in the Error List window in the bottom of the screen.
Run-Time Errors:
These types of errors are exceptions triggered when the code is executing something that is
illegal to vb.net environment. Some of the examples for this are division by zero, trying to access
an nonexistent file, declaring arrays out of bounds etc. Run time errors can be handled using the
vb.net code are displayed using a yellow padding over the code, along with a window specifying
the exception handled, with the troubleshooting tips, the Actions required in detail.
Logical Errors:
These errors are defined as errors that are very hard to find out. The code may compile and run
properly but may produce undesired results. Incorrect for an expression like 2 instead of 20 may
also be considered as a logical error.
UNIT – II
Syntax
For variable_name As [ DataType ] = start To end [ Step step ]
[ Statements to be executed ]
Next
Syntax:
For Each var_name As [ DataType ] In Collection_Object
[ Statements to be executed]
Next
For Each loop is used to read each element from the collection object or an array. The Data
Type represents the type of the variable, and var_name is the name of the variable to access
elements from the array or collection object so that it can be used in the body of For Each loop.
Here, condition represents any Boolean condition, and if the logical condition is true, the single
or block of statements define inside the body of the while loop is executed.
Example –
Module loops
Sub Main()
Dim a As Integer = 10
' while loop execution
While a < 20
Console.WriteLine("value of a: {0}",
a) a=a+1
End While
Console.ReadLine()
End Sub
End Module
Do – While/Until Loop:
It repeats the enclosed block of statements while a Boolean condition is True or until the
condition becomes True. It could be terminated at any time with the Exit Do statement.
The syntax for this loop construct is −
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
Example –
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}",
a) a=a+1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
The program would behave in same way, if you use an Until statement, instead of While –
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
'do loop execution
Do
Console.WriteLine("value of a: {0}",
a) a=a+1
Loop Until (a = 20)
Console.ReadLine()
End Sub
End Module
Generally, the Exit statement is written along with a condition. If the Exit condition is true
inside the loop, it exits from the loop and control transfer to the next statement, followed by the
loop. And if the Exit condition fails for the first time, it will not check any statement inside the
loop and terminates the program.
Example: Write a program to calculate the sum of 10 numbers, and if a negative number is
entered, the For Each loop ends.
Imports System
Module Exit_For
Sub Main()
'Definition of num variable
Dim num As Integer
Dim sum As Double = 0.0
Continue Statement:
In VB.NET, the continue statement is used to skip the particular iteration of the loop and
continue with the next iteration. Generally, the continue Statement is written inside the body of
the For, While and Do While loop with a condition. In the previous section, we learned about the
Exit
Statement. The main difference between the Exit and a Continue Statement is that the Exit
Statement is used to exit or terminate the loop's execution process. In contrast, the Continue
Statement is used to Skip the particular iteration and continue with the next iteration without
ending the loop.
Syntax –
Continue { Do | For | While }
Example: Write a simple program to use the Continue Statement in While End loop.
Imports System
Module Continue_While
Sub Main()
'Declaration and initialization of variable i
Dim i As Integer = 10
'Define the While Loop Condition
While i < 20
If i = 14 Then
Console.WriteLine(" Skipped number is {0}", i)
i += 1 ' skip the define iteration
Continue While
End If
Console.WriteLine(" Value of i is {0}", i)
i += 1 ' Update the variable i by 1
End While
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
GoTo Statement:
In VB.NET, the GoTo statement is known as a jump statement. It is a control statement that
transfers the flow of control to the specified label within the procedure. The GoTo statement uses
labels that must be a valid identifier. The GoTo statement can be used in Select case, decision
control statements, and loops. Syntax –
GoTo Label_1
Here, GoTo is a keyword, and label_1 is a label used to transfer control to a specified label
statement in a program.
Example: Write a program to print the sum of the First ten numbers using the Goto Statement in
VB.NET.
Imports System
Module Goto_For
Sub Main()
'Declaration of local variable
Dim i, n As Integer, Sum As Integer = 0
' Define For Loop Statement
For i = 1 To 10
Console.WriteLine(" Value of i is {0}", i)
Sum = Sum + i 'At each iteration the value of i added to Sum
If i = 5 Then
n = i 'Assign i to n
GoTo total_sum ' Jump to total_sum
End If
Next total_sum:
Console.WriteLine(" Total sum is {0}", Sum)
Console.WriteLine(" GoTo Encounter, when value of i = {0}", n)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
Methods
In visual basic, Method is a separate code block that will contain a series of statements to
perform particular operations. Generally, visual basic Methods are useful to improve the code
reusability by reducing code duplication. Suppose, if we have the same functionality to perform
in multiple places, we can create one method with the required functionality and use it wherever
required in the application.
Methods – Methods are simply member procedures built into the class. In Visual Basic .NET
there are two types of methods Functions and Sub Procedures. Methods help us to handle code in
a simple and organized fashion. Functions return a value, but Sub Procedures does not return any
value. Methods are basically a series of statements that are executed when called. Detail
explanation of Sub Procedures and Functions are given below:
Sub Procedures – In Visual Basic .NET Sub Procedures are the statements enclosed by the Sub
and End Sub statements. Statements are executed when we call the Sub procedure. The
statements within it are executed until the matching End Sub is not found. A Sub procedure
performs actions but does not return a value. The starting point of the program Sub Main(), it is
also a sub procedure.
The control is transferred to Sub Main() Sub procedure automatically when application start
execution.
Or
<Access_Specifier> Function Method_Name(<Parameters>) As <Return_Type>
// Statements to Execute
Return return_val
End Function
Access_Specifier – It is useful to define access levels, i.e., public or private, etc., to allow other
classes to access the method. If we didn’t mention any access modifier, it is private by default.
Method_Name – It must be a unique name to identify the method.
Parameters – The method parameters are useful for sending or receiving data from a method,
and these are enclosed within parentheses and separated by commas. If no parameters require for
a method, we need to define a method with empty parentheses.
Return_Type – It is useful to specify the type of value the method can return.
Example:
Module Module1
Sub Main()
Dim result As String = GetUserDetails("Suresh Dasari", 31)
Console.WriteLine(result)
GetDetails()
Console.ReadLine()
End Sub
Public Sub GetDetails()
Console.WriteLine("Press Enter Key to Exit..")
End Sub
Public Function GetUserDetails(ByVal name As String, ByVal age As Integer) As String
Dim info As String = String.Format("Name: {0}, Age: {1}", name, age)
Return info
End Function
End Module
Example:
Imports System.Console
Module Module1
Public Class demo
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
WriteLine("You are in function add(a,b)")
Return a + b
End Function
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer, ByVal c As
Integer)
WriteLine("You are in function add(a, b, c)")
Return a + b + c
End Function
End Class
Sub Main()
Dim obj As New demo
WriteLine(obj.add(4, 2))
WriteLine(obj.add(4, 5, 1))
WriteLine("press return to exit...")
Read()
End Sub
End Module
ARRAYS
Arrays are useful to store multiple elements of the same data type at contiguous memory
locations and arrays will allow us to store the fixed number of elements sequentially based on the
predefined number of items. An array stores a fixed-size sequential collection of elements of the
same type. All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element. An array can start storing the values
from index 0. Suppose if we have an array with n elements, then it will start storing the elements
from index 0 to n-1.
Arrays can be declared by specifying the type of elements followed by the brackets () like as
shown below
Dim array_name As [Data_Type]();
Here, array_name represents the name of an array and Data_type will represent the data type of
elements to store in an array.
Example;
' Store only int values
Dim numbers As Integer()
' Store only string values
Dim names As String()
Arrays can be initialized by creating an instance of an array with New keyword. By using the
New keyword, we can declare and initialize an array at the same time based on our requirements.
Following are the different ways of declaring and initializing array elements by using New
keyword in a visual basic programming language.
' Declaring and Initializing an array with size of 5
Dim array As Integer() = New Integer(4) {}
' Defining and assigning an elements at the same time
Dim array2 As Integer() = New Integer(4) {1, 2, 3, 4, 5}
' Initialize with 5 elements will indicates the size of an array
Dim array3 As Integer() = New Integer() {1, 2, 3, 4, 5}
' Another way to initialize an array without size
Dim array4 As Integer() = {1, 2, 3, 4, 5}
' Declare an array without initialization
Dim array5 As Integer()
array5 = New Integer() {1, 2, 3, 4, 5}
The elements in an array can be stored and accessed by using the index of the array.
Example:
Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers '
Dim i, j As Integer
' initialize elements of array n '
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
' output each array element's value '
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of
the program. You can declare a dynamic array using the ReDim statement.
Syntax for ReDim statement − ReDim
[Preserve] arrayname(subscripts)
Where,
• The Preserve keyword helps to preserve the data in an existing array, when you resize it.
• arrayname is the name of the array to re-dimension.
• subscripts specifies the new dimension.
Example:
Module arrayApl
Sub Main()
Dim marks() As
Integer ReDim
marks(2) marks(0) =
85 marks(1) = 75
marks(2) = 90
ReDim Preserve
marks(10) marks(3) = 80
marks(4) = 76 marks(5) =
92 marks(6) = 99
marks(7) = 79 marks(8) =
75
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
Multi-Dimensional Arrays
VB.Net allows multidimensional arrays. Multidimensional arrays are also called
rectangular arrays. You can declare a 2-dimensional array of strings as –
Dim twoDStringArray(10, 20) As String
Imports System
Module array_Parameter
Function AddPara(ByVal Arr As Integer(), ByVal size As Integer) As Double
'Declare a local variable.
Dim i As Integer
Dim avg As Double
Dim Sum As Integer = 0
For I = 0 To size - 1
Sum = Sum +
Arr(i) Next avg
= Sum / size
Return avg
End Function
Sub Main()
Dim arrays As Integer() = {50, 10, 20, 5, 4,
25} Dim getAvg As Double getAvg =
AddPara(arrays, 6)
Console.WriteLine("Average sum of array element is {0}", getAvg)
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
UNIT – III
If you click the icon on the top left corner, it opens the control menu, which contains the
various commands to control the form like to move control from one place to another place, to
maximize or minimize the form or to close the form.
Form Properties
Following table lists down various important properties related to a form. These properties can be
set or read during application execution. You can refer to Microsoft documentation for a
complete list of properties associated with a Form control:
S.N Properties Description
1 AcceptButton The button that's automatically activated when you press Enter, no
matter which control has the focus at the time. Usually the OK button on a form is set as
AcceptButton for a form.
2 CancelButton The button that's automatically activated when you hit the Esc key.
Usually, the Cancel button on a form is set as CancelButton for a form.
3 AutoScale This Boolean property determines whether the controls you place
on the form are automatically scaled to the height of the current font. The default value
of this property is True. This is a property of the form, but it affects the controls on the
form.
4 AutoScroll This Boolean property indicates whether scroll bars will be
automatically attached to the form if it is resized to a point that not all its controls are
visible.
5 AutoScrollMinSize This property lets you specify the minimum size of the form,
before the scroll bars are attached.
6 AutoScrollPosition The AutoScrollPosition is the number of pixels by which the two
scroll bars were displaced from their initial locations.
7 BackColor Sets the form background color.
8 BorderStyle The BorderStyle property determines the style of the form's border and the
appearance of the form:
None: Borderless window that can't be resized.
Sizable: This is default value and will be used for resizable
window that's used for displaying regular forms.
Fixed3D: Window with a visible border, "raised" relative to the
main area. In this case, windows can't be resized.
FixedDialog: A fixed window, used to create dialog boxes.
FixedSingle: A fixed window with a single line border.
FixedToolWindow: A fixed window with a Close button only. It
looks like the toolbar displayed by the drawing and imaging
applications.
SizableToolWindow: Same as the FixedToolWindow but
resizable.
In addition, its caption font is smaller than the usual.
8 MinimizeBox By default, this property is True and you can set it to False to hide
the Minimize button on the title bar.
9 MaximizeBox By default, this property is True and you can set it to False to hide
the Maximize button on the title bar.
10 Name This is the actual name of the form.
11 StartPosition This property determines the initial position of the form when it's
first displayed. It will have any of the following values:
CenterParent: The form is centered in the area of its parent form.
CenterScreen: The form is centered on the monitor.
Manual: The location and size of the form will determine its
starting position.
WindowsDefaultBounds: The form is positioned at the default
location and size determined by Windows.
WindowsDefaultLocation: The form is positioned at the
Windows default location and has the dimensions you've set at
design time.
20 Text The text, which will appear at the title bar of the form.
Form Methods
The following are some of the commonly used methods of the Form class. You can refer
to Microsoft documentation for a complete list of methods associated with forms control:
Form Events
Following table lists down various important events related to a form. You can refer to Microsoft
documentation for a complete list of events associated with forms control
Example: Following is an example, which shows how we create two buttons at the time of form
load event and different properties are being set at the same time. Because Form1 is being
referenced within its own event handler, so it will be written as Me instead of using its name, but
if we access the same form inside any other control's event handler, then it will be accessed using
its name Form1. Let's double click on the Form and put the follow code in the opened window.
' Set the position of the button based on the location of button1.
button2.Location = _
New Point(button1.Left, button1.Height + button1.Top + 10)
' Set the start position of the form to the center of the screen.
Me.StartPosition = FormStartPosition.CenterScreen
Controls and Components: Every Visual Basic control consists of three important elements
− Properties which describe the object,
• Methods cause an object to do something and
• Events are what happens when an object does something.
Control Properties
All the Visual Basic Objects can be moved, resized or customized by setting their properties. A
property is a value or characteristic held by a Visual Basic object, such as Caption or Fore Color.
Properties can be set at design time by using the Properties window or at run time by using
statements in the program code.
Object. Property = Value
Where
• Object is the name of the object you're customizing.
• Property is the characteristic you want to change.
• Value is the new property setting.
You can set any of the form properties using Properties Window. Most of the properties can
be set or read during application execution. You can refer to Microsoft documentation for a
complete list of properties associated with different controls and restrictions applied to them.
Control Methods
A method is a procedure created as a member of a class and they cause an object to do
something. Methods are used to access or manipulate the characteristics of an object or a
variable. There are mainly two categories of methods you will use in your classes −
• If you are using a control such as one of those provided by the Toolbox, you can call any
of its public methods. The requirements of such a method depend on the class being used.
• If none of the existing methods can perform your desired task, you can add a method to a
class.
For example, the MessageBox control has a method named Show, which is called in the code
snippet below − Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
MessageBox.Show("Hello, World")
End Sub
End Class
Control Events
An event is a signal that informs an application that something important has occurred.
For example, when a user clicks a control on a form, the form can raise a Click event and call a
procedure that handles the event. There are various types of events associated with a Form like
click, double click, close, load, resize, etc.
Following is the default structure of a form Load event handler subroutine. You can see this code
by double clicking the code which will give you a complete list of the all events associated with
Form control −
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'event handler code goes here
End Sub
Here, Handles MyBase.Load indicates that Form1_Load() subroutine handles Load event.
Similar way, you can check stub code for click, double click. If you want to initialize some
variables like properties, etc., then you will keep such code inside Form1_Load() subroutine.
Here, important point to note is the name of the event handler, which is by default Form1_Load,
but you can change this name based on your naming convention you use in your application
programming.
VB.Net provides a huge variety of controls that help you to create rich user interface.
Functionalities of all these controls are defined in the respective control classes. The control
classes are defined in theSystem.Windows.Forms namespace.
The following table lists some of the commonly used controls −
Sl.No. Control & Description
1 Forms
The container for all the controls that make up the user interface.
2 TextBox
It represents a Windows text box control.
3 Label
It represents a standard Windows label.
4 Button
It represents a Windows button control.
5 ListBox
It represents a Windows control to display a list of items.
6 ComboBox
It represents a Windows combo box control.
7 RadioButton
It enables the user to select a single option from a group of choices when paired
with other RadioButton controls.
8 CheckBox
It represents a Windows CheckBox.
9 PictureBox
It represents a Windows picture box control for displaying an image.
10 ProgressBar
It represents a Windows progress bar control.
11 ScrollBar
It Implements the basic functionality of a scroll bar control.
12 DateTimePicker
It represents a Windows control that allows the user to select a date and a time and
to display the date and time with a specified format.
13 TreeView
It displays a hierarchical collection of labeled items, each represented by a
TreeNode.
14 ListView
It represents a Windows list view control, which displays a collection of items that
can be displayed using one of four different views.
Mouse Events:
Mouse events occur by the actions of the mouse in a Windows form, such as mouse move
and mouse click. The following are the mouse events in Visual Basic.Net.
• MouseDown – occurs when a mouse button is pressed.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles
object.MouseDown Program Body
End Sub
• MouseEnter – occurs when the mouse pointer enters the control.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles object.MouseEnter
Program Body
End Sub
• MouseHover – occurs when the mouse pointer hovers over the control Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles
object.MouseHover Program Body
End Sub
• MouseLeave – occurs when the mouse pointer leaves the control.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles
object.MouseLeave Program Body
End Sub
• MouseMove – occurs when the mouse pointer moves over the control.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles object.MouseMove
Program Body
End Sub
• MouseUp – occurs when the mouse pointer is over the control, and the mouse button is
released.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles object.MouseUp
Program Body
End Sub
• MouseWheel – occurs when the mouse wheel moves and the control has the focus.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles object.MouseWheel
Program Body
End Sub
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
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 −
KeyBoard Events:
Keyboard events occur by the actions of the keyboard in a Windows form, such as key
press and key up. The following are the keyboard events in Visual Basic.Net.
• KeyDown – occurs when a key is pressed down and the control has focus.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles object.KeyDown
Program Body
End Sub
• KeyPress – occurs when a key is pressed and the control has focus.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2) Handles object.KeyPress
Program Body
End Sub
• KeyUp – occurs when a key is released while the control has focus.
Syntax: private sub func_name(alias as Datatype1, alias as Datatype2) Handles
object.KeyUp
Program Body
End Sub
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
• 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
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.
Add the following codes for handling the KeyUP events of the text box txtID.
Panel
You use panels to group other controls, usually to divide a form into regions by function. For
example, you may have a menu form that lets the user select drinks in one panel and what they
want on their sandwich in another.
You can use grouping controls such as panels and group controls to make it clear which controls
are associated—and it makes it easier to handle groups of controls at design time too, because
when you move a panel, all the controls it contains are moved as well. The Panel control is
similar to the GroupBox control; however, only the Panel control can have scroll bars, and only
the GroupBox control displays a caption. To display scroll bars, you set the AutoScroll property
to True. Besides using the BorderStyle property to customize a panel, you also can use the
BackColor and BackgroundImage properties.
Group Boxes
Like panels, group boxes are used to provide a grouping for other controls. Group boxes are
similar to panels, but, as mentioned above, only group boxes display captions and only the panels
can have scroll bars. Group boxes display frames around their contained controls and can display
text in a caption, you set the group box's caption with the Text property.
The usual use for group boxes is to contain radio buttons with panel controls, when you
group radio buttons using group boxes, each set of radio buttons can function independently,
which means that one radio button in each set may be selected.
Menu Control
A menu is located on the menu bar and contains a list of related commands. MainMenu is
the container for the Menu structure of the form and menus are made of MenuItem objects that
represent individual parts of a menu. You can create a main menu object on your form using the
MainMenu control. The following picture shows how to drag the Menustrip Object to the Form.
After drag the Menustrip on your form you can directly create the menu items by type a value
into the "Type Here" box on the menubar part of your form. From the following picture you can
understand how to create each menu items on mainmenu Object.
If you need a separator bar , right click on your menu then go to insertSeparator. After
creating the Menu on the form , you have to double click on each menu item and write the
programs there depends on your requirements. The following Vb.Net program shows how to
show a messagebox when clicking a menu item.
Example
Let us add menu and sub-menu items.
Take the following steps −
• Drag and drop or double click on a MenuStrip control, to add it to the form.
• Click the Type Here text to open a text box and enter the names of the menu items or
submenu items you want. When you add a sub-menu, another text box with 'Type Here'
text opens below it.
• Complete the menu structure shown in the diagram above.
• Add a sub menu Exit under the File menu.
Double-Click the Exit menu created and add the following code to the Click event of
ExitToolStripMenuItem −
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) _
Handles ExitToolStripMenuItem.Click
End
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar. Click on the File Exit to exit from the application
List Box
The function of the List Box in visual basic 2017 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.
Adding Items to a List Box
To add items at design time, start a new project and insert a list box on the form. Right-
click on the list box to access the properties window. Next, click on collection of the Item
property, you will be presented with String Collection Editor whereby you can enter the items
one by one by typing the text and press the Enter key, After clicking on the OK button, the items
will be displayed in the list box.
Items can also be added at runtime using the Add( ) method. For a list box, Item is an
object subordinated to the object ListBox. Item comprises a method called Add() that is used to
add items to the list box. To add an item to a list box, you can use the following syntax:
ListBox.Item.Add(“Text”)
For example, if you wish to add a new item to ListBox1 above, you can key-in the following
statement
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Add(“Microsoft Visual Studio 2017”)
End Sub
The item “Visual Studio 2017” will be added to the end of the list
You can also allow the user to add their own items using the 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
Run the program and click on the Add item button will bring up an input box where the user can
key in the item he or she wants to add to the list
Deleting Items from a List Box
To delete items at design time, simply open the String Collection Editor and delete the items line
by line or all at once using the Delete key.
To delete an item at runtime, you can use the Remove method in the following syntax:
ListBox1.Items.Remove(“text”)
It is illustrated in the following example:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ListBox1.Items.Remove(“Visual Basic 6”)
End Sub
The item “Visual Basic 6” will be removed after running the program. You can also let the user
choose which item to delete.
You can also allow the user to delete their own items using the InputBox function. To add this
capability, insert a button at design time and change its text to Delete Item. Click on the button
and enter the following statements in the code window:
Private Sub BtnDelete_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myitem myitem = InputBox(“Enter your Item
for Deletion”) ListBox1.Items.Remove(myitem)
End Sub
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
Combo Box
The function of the Combo Box 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 combo box to see the items which are presented in a drop-down
list.
Adding Items to a Combo Box
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 following is the runtime interface:
After clicking the handle of the right side of the combo box, the user will be able to view all the
items.
you may add items using the Add() method. For example, if you wish to add an item to Combo
box 1, you can key in the following statement
You can also allow the user to add their own items using the InputBox function, as follows:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim myitem
myitem = InputBox(“Enter your Item”)
ComboBox1.Items.Add(myitem)
End Sub
Removing Items from a Combo Box
To delete items at design time, simply open the String Collection Editor and delete the
items at line by line or all at once using the Delete key.
To delete the items at runtime, you can use the Remove method, as illustrated in the following
example. In this example, add a second button and label it “Remove Items”. Click on this button
and enter the following code:
Private Sub Delete_Click(sender As Object, e As EventArgs) Handles Button2.Click
ComboBox1.Items.Remove(“Visual Basic 6”)
End Sub
The item “Visual Basic 6" will be removed after running the program. You can also let the user
choose which item to delete.
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 Btn_Clr_Click(sender As Object, e As EventArgs) Handles Button2.Click
ComboBox1.Items.Clear()
End Sub
MDI Forms:
MDI stands for Multi Document Interface. If you have ever used Microsoft Word or
Excel the chances are you have used a multi-document interface. Multi-document interfaces
consist of a parent form (also called a container) which contains other forms. For example, when
more than one document is open in some versions of Microsoft Word, each document appears in
its own form, contained within the parent form. The forms within the parent can be moved to any
position within the parent form, but typically cannot be moved outside the confines of the parent.
The accurate acronym of MDI would be multi-form interface or multi-window interface.
The reason for this is that there is nothing that restricts the forms to containing just documents. In
fact, a form in an MDI interface can contain anything that a form in a non-MDI interface can
contain. In fact, recent versions of Microsoft Office (specifically Office 2007) have moved away
from the MDI approach. When multiple documents are opened in the Word 2007, for example,
each document appears in an independent window. That said the MDI approach to user interface
design is extremely useful and popular and a wide range of commercial applications are MDI
based.
The first step in creating an MDI form is to create the parent form. Begin by launching
Visual Studio and creating a new Windows Application project named vbMDI. The new project
will contain a single form. Change the name of this form in the Properties panel to MDIparent.
Also in the
Properties panel, change the IsMdiContainer property to True. You will notice that the form
background changes to dark grey, the default for MDI containers. This form is now ready to act
as the container for the child forms.
Add two more forms to the project using the Visual Studio Add New Item toolbar button:
Edit the properties of the two new forms so that the title texts are Child Form 1 and Child Form2
respectively. Also, use the properties panel to name the forms MDIchild1 and MDIchild2.
The next step is to add the two new forms (MDIchild1 and MDIchild2) to the parent form
(MDIparent). To do this click on the tab for the parent form in Visual Studio and double click on
the form to display the event procedures. We will now write Visual Basic code to add the two
child forms to the container parent form. To do this we will set the MdiParent property of each
child to reference the MDIparent form. Note that because this is the Load event of the actual
parent form, we refer to it with the keyword Me rather than by the form name. Having set the
Mdiparent of each child we then need to display the form using the form Show() method:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
MDIchild1.MdiParent = Me
MDIchild1.Show()
MDIchild2.MdiParent = Me
MDIchild2.Show()
End Sub
After adding the above code to the parent form's Load event, press F5 to build and run the
example. When the application runs the child forms will both appear in the parent form.
Exception Handling
Exception Handling in VB.NET is based on the use of four keywords like try, catch, finally and
throws.
• Try: A Try Block is a block of code which generates different exceptions within the
application. To handle these exceptions thrown in the try block we use catch block. Thus
the try block is always followed by one or more catch blocks.
• Catch: A Catch Block is a block of code that contains the statements which handle the
exceptions by using an exception handler on the statement where the issue occurred. The
catch block is mainly the handling of exception by different Exception Classes defined in
the library of Exceptions.
• Finally: A Finally Block is a block of code that contains statements that are mandatory
statements to be executed irrespective of whether the exception is thrown or not thrown.
Suppose I have to open a file, read the file, write the file and close the file. In the try
block, statements are like open a file, read a file and write a file that may or may not
throw an exception but the file needs to be closed before the program ends. Thus the final
block has always statements like closing the files, closing the database connection, the
closing of program, etc.
• Throw: When an issue occurs this statement throws an exception. This exception may be
build in or user-defined exception.
Syntax –
Try
Catch <Exception Name> As <Exception Type>
[Catch1 Statements] Catch <Exception Name> As <Exception Type>
[Catch2 Statements] Catch <Exception Name> As <Exception Type>
[Catch3 Statements] Finally
[Finally Statements] End Try
Here, there is more than one catch block displayed in the above syntax to catch a different
type of exceptions raised by the try block. It may happen that more than one exception being
thrown by the try block and only one catch block is available, then to catch all the exceptions we
will need one or multiple catch statements. And thus we have written more than one catch
statement in the syntax above.
Exceptions are of different types and these are nothing but classes. The parent class from
where these classes are inherited is System.Exception. There are two Exceptions mainly
1. System.SystemException
2. System.ApplicationException
System.SystemException is a class for all built-in system exceptions or we can say that
when running time error when occurred the system exception classes like
DivideByZeroException, IndexOutOfRangeException, StackOverflowException is instantiated.
System.ApplicationException is a class that executes the exceptions defined by the
programmer or developer withing the application. It throws a user-defined exception which is
derived from this System.ApplicationException class.
Example1 –
Module exceptionProg
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
Example2 – Module
OverFlowProg
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(25,777777777777)
Console.ReadKey()
End Sub
End Module
Syntax –
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
• attributelist is a list of attributes that apply to the class. Optional.
• accessmodifier defines the access levels of the class, it has values as - Public, Protected,
Friend, Protected Friend and Private. Optional.
• Shadows indicate that the variable re-declares and hides an identically named element, or
set of overloaded elements, in a base class. Optional.
• MustInherit specifies that the class can be used only as a base class and that you cannot
create an object directly from it, i.e., an abstract class. Optional.
• NotInheritable specifies that the class cannot be used as a base class.
• Partial indicates a partial definition of the class.
• Inherits specifies the base class it is inheriting from.
• Implements specifies the interfaces the class is inheriting from.
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
Objects
Objects are basic building blocks. An object is a combination of data and methods.
In a OOP program, we create objects. These objects communicate together through
methods. Each object can receive messages, send messages and process data.
There are two steps in creating an object. First, we create a class. A class is a template for
an object. It is a blueprint, which describes the state and behavior that the objects of the class all
share. A class can be used to create many objects. Objects created at runtime from a class are
called instances of that particular class.
Syntax –
Dim object_name as new class_name
Example –
Dim b As new Box
Abstraction: Helps the programmer to handle only the objects by hiding the complex business
problems.
Member Functions and Encapsulation
A member function of a class is a function that has its definition or its prototype within the class
definition like any other variable. It operates on any object of the class of which it is a member
and has access to all the members of a class for that object.
Member variables are attributes of an object (from design perspective) and they are kept private
to implement encapsulation. These variables can only be accessed using the public member
functions.
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
Public Sub setLength(ByVal len As Double)
length = len
End Sub
'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)
'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
A default constructor does not have any parameter, but if you need, a constructor can
have parameters. Such constructors are called parameterized constructors.
A destructor is a special member Sub of a class that is executed whenever an object of its class
goes out of scope.
A destructor has the name Finalize and it can neither return a value nor can it take any
parameters. Destructor can be very useful for releasing resources before coming out of the
program like closing files, releasing memories, etc. Destructors cannot be inherited or
overloaded.
Shared Members of a VB.Net Class
We can define class members as static using the Shared keyword. When we declare a member of
a class as Shared, it means no matter how many objects of the class are created, there is only one
copy of the member.
The keyword Shared implies that only one instance of the member exists for a class. Shared
variables are used for defining constants because their values can be retrieved by invoking the
class without creating an instance of it.
Shared variables can be initialized outside the member function or class definition. You
can also initialize Shared variables inside the class definition.
You can also declare a member function as Shared. Such functions can access only Shared
variables. The Shared functions exist even before the object is created.
Example –
class StaticVar
Public Shared num As
Integer Public Sub count()
num = num + 1
End Sub
Public Shared Function getNum() As Integer
Return num
End Function
Shared Sub Main()
Dim s As StaticVar = New StaticVar()
s.count()
s.count()
s.count()
Console.WriteLine("Value of variable num: {0}", StaticVar.getNum())
Console.ReadKey()
End Sub
End Class
Methods
Methods are functions/procedures defined inside the body of a class. They are used to
perform operations with the attributes of our objects. Methods are essential in encapsulation
concept of the OOP paradigm. For example, we might have a Connect method in our
AccessDatabase class. We need not to be informed how exactly Connect connects to the
database. We only know that it is used to connect to a database.
Example –
Module Example
Class Circle
End Class
Sub Main()
Console.WriteLine(c.Area())
End Sub
End Module
Access modifiers
Access modifiers set the visibility of methods and member fields. Visual Basic has five
access modifiers: Public, Protected, Private, Friend, and ProtectedFriend. Public members can be
accessed from anywhere. Protected members can be accessed only within the class itself and by
inherited and parent classes. Friend members may be accessed from within the same assembly
(exe or DLL). ProtectedFriend is a union of protected and friend modifiers.
Public- Entities declared Public have public access. There are no restrictions on the accessibility
of public entities. You can use Public only at module, namespace, or file level.
Protected- Entities declared Protected have protected access. They are accessible only from
within their own class or from a derived class. Protected access is not a superset of friend
access. You can use Protected only at class level.
Friend- Entities declared Friend have friend access. They are accessible from within the
program that contains their declaration and from anywhere else in the same assembly. You can
use Friend only at module, namespace, or file level.
Protected Friend- Entities declared Protected Friend have both protected and friend access.
They can be used by code in the same assembly, as well as by code in derived classes. The rules
for Protected and Friend apply to ProtectedFriend as well.
Private- Entities declared Private have private access. They are accessible only from within
their declaration context, including from any nested procedures. You can use Private only at
module, namespace, or file level.
UNIT - IV
Inheritance
One of the most important concepts in object-oriented programming is that of inheritance.
Inheritance allows us to define a class in terms of another class which makes it easier to create
and maintain an application. This also provides an opportunity to reuse the code functionality and
fast implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should inherit the
members of an existing class. This existing class is called the base class, and the new class
is referred to as the derived class.
Base & Derived Classes
A class can be derived from more than one class or interface, which means that it can
inherit data and functions from multiple base classes or interfaces.
The syntax used in VB.Net for creating derived classes is as follows −
<access-specifier> Class <base_class>
...
End Class
Class <derived_class>: Inherits <base_class>
...
End Class
Class RectangleTester
Shared Sub Main()
Dim rect As Rectangle = New
Rectangle() rect.setWidth(5)
rect.setHeight(7)
' Print the area of the object.
Console.WriteLine("Total area: {0}", rect.getArea())
Console.ReadKey()
End Sub
End Class
Inheritance Modifiers
By default, all classes can serve as base classes in Visual Basic .NET. However, you can use two
class-level modifiers, called inheritance modifiers, to modify that behavior:
NotInheritable— Prevents a class being used as a base class.
MustInherit— Indicates that the class is intended for use as a base class only.
Note that objects of MustInherit classes cannot be created directly; they can be created only as
base class instances of a derived class.
Polymorphism: The method can be implemented for more number of times we call this as Write
once and use it for many times.
Inheritance-based polymorphism –
Inheritance-based polymorphism works as we've already seen—you can store objects of a
derived class in variables of that class's base class (but you can access only the base class's
members using that variable, unless, as mentioned, a derived class has specifically overridden a
base class's method or property).
Interface-based Polymorphism –
Interfaces provide another way you can accomplish polymorphism in Visual Basic .NET.
To support polymorphism with interfaces, you create an interface and implement it in different
ways in various classes. You can then invoke the implemented method of either kind of object in
the same way.
Overloaded – Overloaded members provide different versions of a property or method that have
the same name, but that accept different number of parameters (or parameters of different types).
Overridden – Overridden properties and methods are used to replace an inherited property or
method. When you override a member from a base class, you replace it. Overridden members
must accept the same data type and number of arguments.
Shadowed – Shadowed members are used to create a local version of a member that has broader
scope. You also can shadow a type with any other type. For example, you can declare a property
that shadows an inherited method with the same name.
If an inherited property or method needs to behave differently in the derived class, it can
be overridden; that is, you can define a new implementation of the method in the derived class.
The following modifiers are used to control how properties and methods are overridden:
Overridable— Allows a property or method in a class to be overridden.
Overrides— Overrides an Overridable property or method.
NotOverridable— Prevents a property or method from being overridden. Note that
public methods are NotOverridable by default.
MustOverride— Requires that a derived class override the property or method.
MustOverride methods must be declared in MustInherit classes.
Example –
Public Class Animal
Protected MainForm As Form1
Public Sub New(ByVal form1 As Form1)
MainForm = form1
End Sub
Public Overridable Sub Breathing()
MainForm.TextBox1.Text = "Breathing..."
End Sub
End Class
Public Class Fish
Inherits Animal
Public Sub New(ByVal form1 As Form1)
MyBase.New(form1)
End Sub
Public Overrides Sub Breathing()
MyBase.MainForm.TextBox1.Text = "Bubbling..."
End Sub
End Class
Interfaces
Interfaces define the properties, methods, and events that classes can implement. Interfaces allow you to
define features as small groups of closely related properties, methods, and events; this reduces
compatibility problems because you can develop enhanced implementations for your interfaces without
exposing existing code. You can add new features at any time by developing additional interfaces and
implementations. Visual Basic .NET introduces the Interface statement, which allows you to define true
interfaces as distinct entities from classes, and to implement them with an improved version of the
Implements keyword.
Classes that implement an interface must implement all its properties, methods, and events. The
following example defines two interfaces. The second interface, Interface2, inherits Interface1 and
defines an additional property and method.
Interface Interface1
Sub sub1(ByVal i As Integer)
End Interface
Interface Interface2
Inherits Interface1 ' Demonstrates interface inheritance. Sub M1(ByVal y As
Integer)
ReadOnly Property Num() As Integer
End Interface
The next example implements Interface1, the interface defined in the previous example:
The final example implements Interface2, including a method inherited from Interface1:
Public Class ImplementationClass2 Implements Interface2
Dim INum As Integer = 0
Sub sub1(ByVal i As Integer) Implements Interface2.Sub1
' Place code here that implements this method.
End Sub
Sub M1(ByVal x As Integer) Implements Interface2.M1
' Place code here to implement this method.
End Sub
ReadOnly Property Num() As Integer Implements _
Interface2.Num
Get
Num = INum
End Get
End Property
End Class
Abstract classes and methods
Abstract classes cannot be instantiated. If a class contains at least one abstract method, it must be
declared abstract too. Abstract methods cannot be implemented, they merely declare the methods'
signatures. When we inherit from an abstract class, all abstract methods must be implemented by
the derived class. Furthermore, these methods must be declared with the same of less restricted
visibility.
Unlike Interfaces, abstract classes may have methods with full implementation and may also
have defined member fields. So abstract classes may provide a partial implementation.
Programmers often put some common functionality into abstract classes. And these abstract
classes are later subclassed to provide more specific implementation.
Formally put, abstract classes are used to enforce a protocol. A protocol is a set of operations,
which all implementing objects must support.
Example –
Module Example
MustInherit Class Drawing
Protected x As Integer = 0
Protected y As Integer = 0
Public MustOverride Function Area() As Double
Public Function GetCoordinates() As String
Return String.Format("x: {0}, y: {1}", _
Me.x, Me.y)
End Function
End Class
Class Circle
Inherits Drawing