0% found this document useful (0 votes)
36 views73 pages

Bca VBP

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 73

1) Define dot net? Explain dot Net framework architecture?

Introduction to DOTNET Framework:


DOTNET is a platform created by Microsoft for building different types of applications
using different languages on the DOTNET Framework.
DOTNET Framework is a collection of all the tools, CLR and Base Class Library.

DOTNET Framework Architecture

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

.NET APIs for Task -Based Async

2012
4.5
Store/UWP apps Model

Parallel LINQ Task Parallel

2010
4.0
Library

2007
3.5
LINQ Entity Framework

WCF WPF Card

2006
WF

3.0
Space

WinForms ASP.NET

.NET Framework 2.0


ADO.NET

2005
Framework Class Library

Common Language Runtime

.NET Framework 1.0


The first version of the .NET Framework was released on 13 February 2002.

.NET Framework 1.1


Version 1.1 was published on 3 April 2003. Changes in 1.1 are –
• Built-in support for mobile ASP.NET controls, which was previously available as an add-
on
• Enables Code Access Security in ASP.NET applications
• Built-in support for ODBC and Oracle Database, which was previously available as an
addon
• .NET Compact Framework, a version of the .NET Framework for small devices 
Internet Protocol version 6 support

.NET Framework 2.0


Version 2.0 was released on 22 January 2006. Changes in 2.0 –
• Full 64-bit computing support for both the x64 and the IA-64 hardware platforms
• Microsoft SQL Server integration: Instead of using T-SQL, one can build stored
procedures and triggers in any of the .NET-compatible languages
• New personalization features for ASP.NET, such as support for themes, skins, master
pages and webparts
• Membership provider
• Partial classes
• Nullable types
• Anonymous methods
• Data tables
• Common Language Runtime (CLR) 2.0
• Language support for generics built directly into the .NET CLR

.NET Framework 3.0


.NET Framework 3.0, formerly called WinFX was released on 21 November 2006. There are
no major architectural changes included with this release; .NET Framework 3.0 uses the same
CLR as .NET Framework 2.0. .NET Framework 3.0 consists of four major new components:
• Windows Presentation Foundation (WPF), formerly code-named Avalon: A new user
interface subsystem and API based on XAML markup language, which uses 3D
computer graphics hardware and Direct3D technologies
• Windows Communication Foundation (WCF), formerly code-named Indigo: A
serviceoriented messaging system which allows programs to interoperate locally or
remotely similar to web services
• Windows Workflow Foundation (WF): Allows building task automation and integrated
transactions using workflows
• Windows CardSpace, formerly code-named InfoCard: A software component which
securely stores a person's digital identities and provides a unified interface for choosing
the identity for a particular transaction, such as logging into a website
.NET Framework 3.5
Version 3.5 of the .NET Framework was released on 19 November 2007. As with .NET
Framework 3.0, version 3.5 uses Common Language Runtime (CLR) 2.0, that is, the same
version as .NET Framework version 2.0. This version adds some methods and properties to the
BCL classes in version 2.0 which are required for version 3.5 features such as Language
Integrated Query (LINQ).

.NET Framework 4.0


Key focuses for this version are:
• Parallel Extensions to improve support for parallel computing, which target multi-core or
distributed systems. To this end, technologies like PLINQ (Parallel LINQ), a parallel
implementation of the LINQ engine, and Task Parallel Library, which exposes parallel
constructs via method calls, are included.
• New Visual Basic .NET and C# language features, such as implicit line continuations,
dynamic dispatch, named parameters, and optional parameters  Support for Code
Contracts.
• Introduced Common Language Runtime (CLR) 4.0

.NET Framework 4.5


.NET Framework 4.5 was released on 15 August 2012. A set of new or improved features
were added into this version.
Core features
• Ability to limit how long the regular expression engine will attempt to resolve a regular
expression before it times out.
• Ability to define the culture for an application domain.
• Console support for Unicode (UTF-16) encoding.
• Support for versioning of cultural string ordering and comparison data.
• Better performance when retrieving resources.

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.

Name Space:- Namespace has two basic functionality as follows


 Namespace Logically group types. Example System.Web.UI logically groups our UI
related features.
 In Object Oriented world may time its possible that programmers will use the same class
name.

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.

4) explain visual studio IDE?

Visual Studio Integrated Development Environment:


Visual Studio is an Integrated Development Environment(IDE) developed by
Microsoft to develop GUI (Graphical User Interface), console, Web applications, web apps,
mobile apps, and web services, etc. An integrated development environment (IDE) is a feature-
rich program that supports many aspects of software development. The Visual Studio IDE is a
creative launching pad that you can use to edit, debug, and build code, and then publish an app.
Over and above the standard editor and debugger that most IDEs provide, Visual Studio includes
compilers, code completion tools, graphical designers, and many more features to enhance the
software development process.
An integrated development environment (IDE) is a software application that provides
comprehensive facilities to computer programmers for software development. An IDE normally
consists of at least a source code editor, build automation tools and a debugger.

List the components of the IDE screen of visual basic


• The Visual Basic IDE is made up of a number of components.
• Menu Bar.
• Tool Bar.
• Solution Explorer.
• Properties window.
• Form Layout Window.
• Toolbox.
• Form Designer.
• Code Editor
• Output Window
Various Menus in Visual Studio: Menus contain groups of related commands (also called menu
items) that, when selected, cause the IDE to perform specific actions (e.g., open a window, save a
file, print a file and execute a program). For example, new projects can be created by selecting
File > New Project.... A user can find a lot of menus on the top screen of Visual Studio. Menu
bar in Visual Basic.net consist of the commands that are used for constructing a software code.
These commands are listed as menus and sub menus. The following are the menu items –

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.

Introduction to Visual Basic:


Programming means designing a set of instructions to instruct the computer to carry out certain
jobs that are very much faster than human beings can do. The earliest programming language is
called machine language which uses the binary code to communicate with the computer.
However, the machine language is extremely difficult to learn.
Visual Basic is an event-driven programming language released by Microsoft in 1991. It
evolved from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose
Symbolic Instruction Code. Since then Microsoft has released many versions of Visual Basic,
from Visual Basic 1.0 to the final version Visual Basic 6.0. Visual Basic is a user-friendly
programming language designed for beginners, and it enables anyone to develop GUI window
applications easily.
In 2002, Microsoft released Visual Basic.NET (VB.NET) to replace Visual Basic 6.
VB.NET is a fully object-oriented programming language implemented in the .NET Framework.
It was created to cater for the development of the web as well as mobile applications.

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.

Differences between Visual Basic and Visual Basic.NET:

VB .NET Visual Basic


It stands for Visual Basic. Network Enables It is a programming language developed
Technology. It is also developed by Microsoft, and this by Microsoft for the fastest development
language was based on the .Net Framework. of a window-based operating system as
Furthermore, it is specially designed for VB well as applications.
developers.
VB is the predecessor of VB.NET and
It is a modern, fully object-oriented language that
was not an object-oriented language. So,
replaced VB6.
it is not actively maintained.
A VB.NET uses the Common Language Runtime
(CLR) component of .Net Framework at runtime. It has Visual Basic uses the VB-Runtime
better features and design implementation as compared environment.
to VBRuntime.
It is a compiled language It is an Interpreter based language
It does not support backward compatibility. It supports backward compatibility.
It is a type-safe language. It is not a type-safe language.
Data Connectivity and handling are done
In VB.NET, data is handled using the ADO.net
through DAO, RDO, and ADO (ActiveX
protocol.
Data Object) protocol,
In VB, most of the parameters are passed
In the VB.Net parameter are passed by a default value.
by reference.
A Multithreaded application can be developed in It does not support the multithread
VB.NET. concept.
In VB.NET, operator is a special symbol that tells the compiler to perform the specific
logical or mathematical operation on the data values. The data value itself (which can be either a
variable or a constant) is called an operand, and the Operator performs various operations on
the operand.

Different Types of VB.NET Operators


Following are the different types of Operators available in VB.NET:
• Arithmetic Operators
• Comparison Operators
• Logical and Bitwise Operators
• Assignment Operators
• Concatenation Operators

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:

Operator Description Example


s
It is an exponentiation Operator that is used to raises one operand to Y ^ X (X to the
^
the power of another operand. power Y)
The addition Operator is used to add numeric data, as well as
+ X+Y
concatenate two string variables.
It is a subtraction Operator, which is used to subtract the second
- X–Y
operand from the first operand.
* The multiplication Operator is used to multiply the operands X*Y
It is a division Operator used to divide one operand by another
/ X/Y
operand and returns a floating-point result.
It is an integer division Operator, which is similar to division
\ Operator, except that it returns an integer result while dividing one X\Y
operand to another operand.
It is a modulo (Modulus) Operator, which is used to divide two
Mod X Mod Y
operands and returns only a remainder.
Comparison Operators
As the name suggests, the Comparison Operator is used to compare the value of two
variables or operands for the various condition such as greater, less than or equal, etc. and returns
a Boolean value either true or false based on the condition.

Operato Description Example


r
It checks whether the value of the two operands is equal; If
= (A = B)
yes, it returns a true value, otherwise it shows False.
It is a Non-Equality Operator that checks whether the value
(A <> B), check Non-
<> of the two operands is not equal; it returns true; otherwise, it
Equality
shows false.
A greater than symbol or Operator is used to determine
whether the value of the left operand is greater than the (A > B); if yes, TRUE,
>
value of the right operand; If the condition is true, it returns Else FALSE
TRUE; otherwise, it shows FALSE value.
It is a less than symbol which checks whether the value of (A < B); if the condition
the left operand is less than the value of the right operand; If is true, returns TRUE
<
the condition is true, it returns TRUE; otherwise, it shows else
FALSE FALSE
It is greater than equal to which checks two conditions
whether the first operand is greater than or equal to the
>= A >= B
second operand; if yes, it returns TRUE; otherwise, it shows
False.
This symbol represents less than equal to which determines
the first operand is less than or equal to the second operand,
<= A <= B
and if the condition is true, it returns TRUE; otherwise, it
shows FALSE.
The Is Operator is used to validate whether the two objects
reference the same variable or object; If the test is true, it
Is returns True; otherwise, the result is False. In short, it result = obj1 Is obj2
checks the equality of the objects. An Is Operator is also
used to determine whether the object refers to a valid object.
The IsNot Operator is similar to Is Operator, except that the
IsNot two object references the different object; if yes, the result is Result = obj1 IsNot obj2
True; otherwise, the result is False.
result = string Like the
The Like Operator is used to check the pattern expression of pattern, the pattern
Like string variable; And if the pattern matched, the result is represents the series of
True; otherwise, it returns False. characters used by Like
Operator.

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.

Operato Description Example


r
The And Operator represents, whether both the operands are true; the (A And B),
And
result is True. result = False
It is an Or Operator that returns a true value; if anyone operand is true (A Or B), result
Or
from both the operands. = True
Not A
The Not Operator is used to reverse the logical condition. For Or
Not example, if the operand's logic is True, it reveres the condition and Not(A And B)
makes it False. is
True

Assignment Operators
The Assignment Operators are used to assign the value to variables in VB.NET.

Operato Description Example


r
X = 5, X assign a value 5
It is a simple assignment Operator used to assign a X = P + Q, (P + Q)
=
rightside operand or value to a left side operand. variables or value assign
to X.

+= An Add AND assignment Operator is used to add the X += 5, which means X=


X+5 ( 5 will add and
value of the right operand to the left operand. And the assign to X and then
result is assigned to the left operand. result saved to Left X
operand)
It is a Subtract AND assignment Operator, which subtracts
X -= P, which is same as X
-= the right operand or value from the left operand. And then,
=X-P
the result will be assigned to the left operand.
It is a Multiply AND assignment Operator, which
X *= P, which is same as X
*= multiplies the right operand or value with the left operand.
=X-P
And then, the result will be assigned to the left operand.
It is a Divide AND assignment Operator, which divides
the left operand or value with the right operand. And then, X /= P, which is same as X
/=
the result will be assigned to the left operand (in floating- = X - P
point).
It is a Divide AND assignment Operator, which divides
the left operand or value with the right operand. And then, X \= P, which is same as X
\=
the result will be assigned to the left operand (in integer- = X - P
point division).
It is an expression AND assignment Operator, which
raises the left operand or value to the right operand's X ^= P, which is same as X
^=
power. And then, the result will be assigned to the left = X ^ P
operand.
It is a concatenate string assignment Operator used to
bind the right-hand string or variable with the left-hand Str &= name, which is
&=
string or variable. And then, the result will be assigned same as Str = Str & name
to the left operand.

Concatenation Operators
In VB.NET, there are two concatenation Operators to bind the operands:

Operato Description Example


r
Result = Wel
It is an ampersand symbol that is used to bind two or more operand
& come,
& together. Furthermore, a nonstring operand can also be concatenated
Result =
with a string variable ( but in that case, Option Strict is on).
Welcome
+ It is also used to add or concatenate two number or string. Result = Wel
+ come,
Result =
Welcome

Introduction to Problem Solving and Control Statements:


Introduction:
Before writing a program to solve a problem, you should have a thorough understanding of the
problem and a carefully planned approach. When writing a program, it's also important to know
the available building blocks and to use proven program-construction principles. The If...Then,
If...Then...Else, Do While...Loop, While...End While and Do Until...Loop statements—five of
the building blocks that allow you to specify the logic required for methods to perform their
tasks.

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.

VB.NET provides the following conditional or decision-making statements.


• If-Then Statement
• If-Then Else Statement
• If-Then ElseIf Statement
• Select Case Statement
• Nested Select Case Statements
If-Then Statement –
The If-Then Statement is a control statement that defines one or more conditions, and if
the particular condition is satisfied, it executes a piece of information or statements.
Syntax:
1. If condition Then
2. [Statement or block of Statement]
3. End If

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 1: Write a simple program to print a statement in VB.NET.


Module1.vb
Module Module1
' Declaration of variable str
Dim str As String = "JavaTpoint"
Sub Main()
' if str equal to "JavaTpoint", below Statement will be executed.
If str = "JavaTpoint" Then
Console.WriteLine("Welcome to the JavaTpoint")
End If
Console.WritLine("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.

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 1: Write a program to check whether the number is even or odd.


If_Else_statment.vb
Module If_Else_statement
Sub Main()
Dim num As Integer
Console.WriteLine("Enter the Number")
num = Console.ReadLine() 'read data from console
If (num Mod 2 = 0) Then ' if condition is true, print the if
statement Console.WriteLine("It is an even number")
Else 'otherwise, Else statement is executed.
Console.WriteLine("It is an odd 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

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.

VB.NET If-Then-ElseIf statement


The If-Then-ElseIf Statement provides a choice to execute only one condition or
statement from multiple statements. Execution starts from the top to bottom, and it checked for
each If condition. And if the condition is met, the block of If the statement is executed. And if
none of the conditions are true, the last block is executed. Following is the syntax of If-Then-
ElseIf Statement in VB.NET as follows:
Syntax
If(condition 1)Then
' Executes when condition 1 is true
ElseIf( condition 2)Then
' Executes when condition 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the condition 3 is true
Else
' executes the default statement when none of the above conditions is true.
End If

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 1: Write a program to show the uses of If... ElseIf statements.


if_elseIf.vb
Module if_elseIf
Sub Main()
Dim var1 As Integer

Console.WriteLine(" Input the value of var1: ")


var1 = Console.ReadLine()
If var1 = 20 Then
'if condition is true then print the following statement'
Console.WriteLine(" Entered value is equal to 20")
ElseIf var1 < 50 Then
Console.WriteLine(" Entered value is less than 50")

ElseIf var1 >= 100 Then


Console.WriteLine(" Entered value is greater than 100")
Else
'if none of the above condition is satisfied, print the following statement
Console.WriteLine(" Value is not matched with above condition")
End If
Console.WriteLine(" You have entered : {0}", var1)
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.

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

Example 1: Write a program to use a nested select case statement in VB.NET.


Module1.vb
Module Module1
Sub Main()
Dim x As Integer = 10, y As Integer = 5
Select Case x
Case 10
Console.WriteLine("X Value: 10")
Select Case y
Case 5
Console.WriteLine("Nested Switch Value: 5")
Select Case y - 2
Case 3
Console.WriteLine("Another Nested Switch Value: 3")
End Select
End Select
Case 15
Console.WriteLine("X Value: 15")
Case 20
Console.WriteLine("X Value: 20")
Case Else
Console.WriteLine("Not Known")
End Select
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub End
Module

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

Looping or Repetition Statements


A Loop is used to repeat the same process multiple times until it meets the specified
condition in a program. By using a loop in a program, a programmer can repeat any number of
statements up to the desired number of repetitions. A loop also provides the suitability to a
programmer to repeat the statement in a program according to the requirement.

Advantages of VB.NET loop


• It provides code iteration functionality in a program.
• It executes the statement until the specified condition is true.
• It helps in reducing the size of the code.
• It reduces compile time.

VB.Net provides following types of loops to handle looping requirements.

Loop Type Description


It repeats a group of statements a specified number of times and
For...Next a loop index counts the number of loop iterations as the loop
executes.
It repeats a group of statements for each element in a collection.
For Each...Next This loop is used for accessing and manipulating all elements in
an array or a VB.Net collection.
It executes a series of statements as long as a given condition is
While... End While
True.
It repeats the enclosed block of statements while a Boolean
Do Loop condition is True or until the condition becomes True. It could
be terminated at any time with the Exit Do statement.

For Next Loop


A For Next loop is used to repeatedly execute a sequence of code or a block of code until a
given condition is satisfied. A For loop is useful in such a case when we know how many times a
block of code has to be executed. In VB.NET, the For loop is also known as For Next Loop.

Syntax
For variable_name As [ DataType ] = start To end [ Step step ]
[ Statements to be executed ]
Next

For Next loop in detail.


• For: It is the keyword that is present at the beginning of the definition.
• variable_name: It is a variable name, which is required in the For loop Statement. The value
of the variable determines when to exit from the For-Next loop, and the value should only be
a numeric.
• [Data Type]: It represents the Data Type of the variable_name.
• start To end: The start and end are the two important parameters representing the initial and
final values of the variable_name. These parameters are helpful while the execution begins,
the initial value of the variable is set by the start. Before the completion of each repetition,
the variable's current value is compared with the end value. And if the value of the variable is
less than the end value, the execution continues until the variable's current value is greater
than the end value. And if the value is exceeded, the loop is terminated.
• Step: A step parameter is used to determine by which the counter value of a variable is
increased or decreased after each iteration in a program. If the counter value is not specified;
It uses 1 as the default value.
• Statements: A statement can be a single statement or group of statements that execute during
the completion of each iteration in a loop.
• Next: In VB.NET a Next is a keyword that represents the end of the For loop's

For Each Loop


In the VB.NET, For Each loop is used to iterate block of statements in an array or collection
objects. Using For Each loop, we can easily work with collection objects such as lists, arrays,
etc., to execute each element of an array or in a collection. And when iteration through each
element in the array or collection is complete, the control transferred to the next statement to end
the loop.

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.

While – End Loop


The While End loop is used to execute blocks of code or statements in a program, as
long as the given condition is true. It is useful when the number of executions of a block is not
known. It is also known as an entry-controlled loop statement, which means it initially checks
all loop conditions. If the condition is true, the body of the while loop is executed. This process
of repeated execution of the body continues until the condition is not false. And if the condition
is false, control is transferred out of the loop.
Syntax:
While [condition]
[ Statement to be executed ]
End While

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

Loop Control Statements


Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
VB.Net provides the following control statements. Click the following links to check their
details.
Control Statement Description
Terminates the loop or select case statement and transfers
Exit statement execution to the statement immediately following the loop or select
case.
Causes the loop to skip the remainder of its body and immediately
Continue statement
retest its condition prior to reiterating.
Transfers control to the labeled statement. Though it is not advised
GoTo statement
to use GoTo statement in your program.
Exit Statement
In VB.NET, the Exit statement is used to terminate the loop (for, while, do, select case, etc.) or
exit the loop and pass control immediately to the next statement of the termination loop.
Furthermore, the Exit statement can also be used in the nested loop to stop or terminate the
execution of the inner or outer loop at any time, depending on our requirements.
Syntax:
Exit { Do | For | Function | Property | Select | Sub | Try | While }

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

'Execution of For loop


For i As Integer = 1 To 10
'Accept a number from the user
Console.WriteLine("Enter a number : ")
num = Console.ReadLine()
' If the user enters a negative number, the loop terminates
If num < 0 Then
Exit For ' terminate the For
loop End If sum +=
num
Next
Console.WriteLine(" Exit from the For loop when (num < 0) is: {0}", num)
Console.WriteLine(" Total sum is : {0}", sum)
Console.WriteLine(" Press any key to exit from the Console Screen")
Console.ReadKey()
End Sub
End Module

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.

Syntax of Visual Basic Methods


In visual basic, we can create the Methods either by using Sub or Function keywords like as
shown below. If we create a method with Sub keyword that will not allow us to return any value.
If you want to return any value, you need to use Function keyword to create the method.
<Access_Specifier> Sub Method_Name(<Parameters>)
// Statements to Execute
End Sub

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

Function Returning a Value


In VB.Net, a function can return a value to the calling code in two ways −
• By using the return statement
• By assigning the value to the function name Example:
Module myfunctions
Function FindMax(ByVal num1 As Integer, ByVal num2 As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num1 > num2) Then
result = num1 Else
result = num2
End If
FindMax = result
End Function
Sub Main()
Dim a As Integer = 100
Dim b As Integer =
200 Dim res As Integer
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module

Recursive Function – A function can call itself. This is known as recursion.


Example:
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration */
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
Return result
End If
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module

Passing Parameters by Value


This is the default mechanism for passing parameters to a method. In this mechanism,
when a method is called, a new storage location is created for each value parameter. The values
of the actual parameters are copied into them. So, the changes made to the parameter inside the
method have no effect on the argument. In VB.Net, you declare the reference parameters using
the ByVal keyword. Example:
Module paramByval
Sub swap(ByVal x As Integer, ByVal y As
Integer) Dim temp As Integer temp = x '
save the value of x x = y ' put y into x y
= temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module

Passing Parameters by Reference


A reference parameter is a reference to a memory location of a variable. When you pass
parameters by reference, unlike value parameters, a new storage location is not created for these
parameters. The reference parameters represent the same memory location as the actual
parameters that are supplied to the method. In VB.Net, you declare the reference parameters
using the ByRef keyword.
Example:
Module paramByref
Sub swap(ByRef x As Integer, ByRef y As
Integer) Dim temp As Integer temp = x '
save the value of x x = y ' put y into x y
= temp 'put temp into y
End Sub
Sub Main()
' local variable definition
Dim a As Integer = 100
Dim b As Integer = 200
Console.WriteLine("Before swap, value of a : {0}", a)
Console.WriteLine("Before swap, value of b : {0}", b)
' calling a function to swap the values '
swap(a, b)
Console.WriteLine("After swap, value of a : {0}", a)
Console.WriteLine("After swap, value of b : {0}", b)
Console.ReadLine()
End Sub
End Module

Method Overloading: Method Overloading allows us to write different versions of a method


(i.e. a single class can contain more than one methods (Sub / Functions) of same name but of
different implementation). And compiler will automatically select the appropriate method based
on parameters passed.

Consider following points in order to implement/understand method overloading :


All the overloaded methods must be of same procedure type (either only Sub or only Function).
Allowed :
Public Overloads Function add(ByVal a As Integer, ByVal b As
Integer) Public Overloads Function add(ByVal a As Long, ByVal b
As Long) Not Allowed :
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
Public Overloads Sub add(ByVal a As Long, ByVal b As Long)
Don't repeat same parameters with same data types in parameter, it will show an error
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
Overloaded methods must have different number parameters and/or Different data types in the
parameters
Different number of parameters
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer, ByVal c As Integer)
Different data type in parameters
Public Overloads Function add(ByVal a As Integer, ByVal b As Integer)
Public Overloads Function add(ByVal a As Long, ByVal b As Long)

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

A 3-dimensional array of Integer variables –


Dim threeDIntArray(10, 10, 10) As Integer

2-Dimensional array example:


Module arrayApl
Sub Main()
' an array with 5 rows and 2 columns
Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}}
Dim i, j As Integer
' output each array element's value '
For i = 0 To 4
For j = 0 To 1
Console.WriteLine("a[{0},{1}] = {2}", i, j, a(i, j))
Next j
Next i
Console.ReadKey()
End Sub
End Module
Access Array Elements with Foreach Loop
In visual basic, same as for loop we can use For Each loop to iterate through array
elements and access the values of an array based on our requirements.
Example:
Module Module1
Sub Main()
Dim array As Integer() = New Integer(4) {1, 2, 3, 4, 5}
For Each i As Integer In array
Console.WriteLine(i)
Next
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

Passing Array as a Parameter


Let's create a program that parses an array as a pass parameters in a function.

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

Windows Forms GUI:-


To creating a Window Forms Application by following the following steps in MicrosoftVisual
Studio: File  New Project  Windows Forms Applications. Finally, select OK, Microsoft
Visual Studio creates your project and displays window Form with a name Form1. Visual Basic
Form is the container for all the controls that make up the user interface. Every window you see
in a running visual basic application is a form, thus the terms form and window describe the
same entity. Visual Studio creates a default form for you when you create a Windows Forms
Application. Every form will have title bar on which the form's caption is displayed and there
will be buttons to close, maximize and minimize 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:

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:

S.N. Method Name Description


1 Activate Activates the form and gives it focus.
2 ActivateMdiChild Activates the MDI child of a form.
3 AddOwnedForm Adds an owned form to this form.
4 BringToFront Brings the control to the front of the z-order.
5 CenterToParent Centers the position of the form within the bounds of the parent form.
6 CenterToScreen Centers the form on the current screen.
7 Close Closes the form.
8 Contains Retrieves a value indicating whether the specified control is
a
child of the control.
9 Focus Sets input focus to the control.
10 Hide Conceals the control from the user.
11 Refresh Forces the control to invalidate its client area and
immediately
redraw itself and any child controls.
12 SetAutoScrollMargin Sets the size of the auto-scroll margins.
13 SetDesktopBounds Sets the bounds of the form in desktop coordinates.
14 SetDesktopLocation Sets the location of the form in desktop coordinates.
15 SetDisplayRectLocation Positions the display window to the specified value.
16 Show Displays the control to the user.
17 ShowDialog Shows the form as a modal dialog box.

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

Sl.No. Event Description


1 Activated Occurs when the form is activated in code or by the user.
2 Click Occurs when the form is clicked.
3 Closed Occurs before the form is closed.
4 Closing Occurs when the form is closing.
5 DoubleClick Occurs when the form control is double-clicked.
6 DragDrop Occurs when a drag-and-drop operation is completed.
7 Enter Occurs when the form is entered.
8 GotFocus Occurs when the form control receives focus.
9 HelpButtonClicked Occurs when the Help button is clicked.
10 KeyDown Occurs when a key is pressed while the form has focus. 11
KeyPress Occurs when a key is pressed while the form has focus.
12 KeyUp Occurs when a key is released while the form has focus.
13 Load Occurs before a form is displayed for the first time.
14 LostFocus Occurs when the form loses focus.
15 MouseDown Occurs when the mouse pointer is over the form and a mouse button
is pressed.
16 MouseEnter Occurs when the mouse pointer enters the form.
17 MouseHover Occurs when the mouse pointer rests on the form.
18 MouseLeave Occurs when the mouse pointer leaves the form.
19 MouseMove Occurs when the mouse pointer is moved over the form.
20 MouseUp Occurs when the mouse pointer is over the form and a mouse
button
is released.
21 MouseWheel Occurs when the mouse wheel moves while the control has focus.
22 Move Occurs when the form is moved.
23 Resize Occurs when the control is resized.
24 Scroll Occurs when the user or code scrolls through the client area.
25 Shown Occurs whenever the form is first displayed.

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.

Public Class Form1


Private Sub Form1_Load(sender AsObject, e As EventArgs) Handles
MyBase.Load ' Create two buttons to use as the accept and cancel buttons.
Dim button1 As New Button()
Dim button2 As New Button()
' Set the text of button1 to "OK".
button1.Text="OK"

' Set the position of the button on the form.


button1.Location = New Point(10, 10)

'Setthe text of button2 to "Cancel".


button2.Text="Cancel"

' 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 caption bar text of the form.


Me.Text="tutorialspoint.com"

' Display a help button on the form.


Me.HelpButton = True

'Define the border style of the form to a dialog box.


Me.FormBorderStyle=FormBorderStyle.FixedDialog
' Set the MaximizeBox to false to remove the maximize box.
Me.MaximizeBox = False

'Set the MinimizeBox to false to remove the minimize box.


Me.MinimizeBox=False

' Set the accept button of the form to button1.


Me.AcceptButton = button1

'Set the cancel button of the form to button2.


Me.CancelButton=button2

' Set the start position of the form to the center of the screen.
Me.StartPosition = FormStartPosition.CenterScreen

'Set window width and height


Me.Height=300
Me.Width=560

' Add button1 to the form.


Me.Controls.Add(button1)

'Add button2 to the form.


Me.Controls.Add(button2)
End Sub End
Class

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.

Event Handling in VB.NET


The events in a Visual Basic.Net program are of two types: user generated events and
system generated events. The user-generated events occur when the user actions key press,
clicks, mouse movements, etc. are happening. System generated events are the notifications in
the computer. An event in a program is an action which occurs when clicking on a button, typing
some texts or moving the mouse and that calls a function or causing for another event. VB.Net is
an event optimized programming language, so it is called an event-driven programming
language. VB.Net mainly provide the following two events.
• Mouse Events
• Keyboard Events

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 −

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

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.

Private Sub txtID_KeyUP(sender As Object, e As KeyEventArgs) _


Handles txtID.KeyUp

If (Not Char.IsNumber(ChrW(e.KeyCode))) 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 Char.IsNumber(ChrW(e.keyCode))) Then
MessageBox.Show("Enter numbers for age")
txtAge.Text = " "
End If
End Sub

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 insertSeparator. 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

Checked List Boxes


Windows forms checked list boxes are derived from standard list boxes, except that they also
support a checkbox for each item, As with standard list boxes, you can access the items in a
checked list box using the Items property. To check an item, the user has to double-click a
checkbox by default, unless you set the CheckOnClick property to True, in which case it only
takes one click.
You can handle the checked items with the CheckedItems property and the
CheckedIndices property. You also can use the GetItemChecked method to verify if an item is
checked. And you can use the ItemCheck event to handle check events, and the
SetItemChecked method to check or uncheck items.
Checked list boxes also can support three states with the CheckState enumeration: Checked,
Indeterminate, and Unchecked. (Note that you must set the state of Indeterminate in the code
because the user interface does not provide a way of doing so.) To use three-state checkboxes,
you use the GetItemCheckState and SetItemCheckState methods instead of GetItemChecked
and SetItemChecked methods.

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

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


ComboBox1.Items.Add(“Visual Studio 2017")
End Sub

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.

Some of VB.NET Exception Classes and its usage.


• System.IndexOutOfRangeException: This exception handles the errors caused by an array
index which is out of range.s Suppose we have an array of 5 array lengths and we loop this 6
times the 6th time the program will through IndexOutOfRangeException.
• System.DivideByZeroException: This exception handles the errors caused when a number
is divided by zero which is against the universal rule that a number being divided by zero will
result in an abnormal termination of the program.
• System.FormatException: This exception handles the errors caused when the user inputs a
character or a string when asked for a number or integer. say the user needs to enter 5 but
inputs say ‘y’ then this exception will occur.

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

Lets now create our own Customized Exceptions


In the below program, we will check whether the number is even or odd.
Logic: 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.
Module EvenorOddNo
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

Object Oriented Programming Language (OOP)

OOP can be defines as Object-oriented programming is a programming technique


that involves structuring a program around special, user-defined data types called classes.
Classes are used to break a problem up into a set of objects that interact with each other. A
class consists of both the data and subprograms, called methods, which describe the object's
behavior. Concepts of OOP:
• Classes
• Objects
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism
Class – Class is a user defined data type, Class is collection of data members and member
functions.

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

Public Sub setBreadth(ByVal bre As Double)


breadth = bre
End Sub

Public Sub setHeight(ByVal hei As Double)


height = hei
End Sub
Public Function getVolume() As Double
Return length * breadth * height
End Function
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.setLength(6.0)
Box1.setBreadth(7.0)
Box1.setHeight(5.0)

'box 2 specification
Box2.setLength(12.0)
Box2.setBreadth(13.0)
Box2.setHeight(10.0)

' volume of box 1


volume = Box1.getVolume()
Console.WriteLine("Volume of Box1 : {0}", volume)

'volume of box 2
volume = Box2.getVolume()
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module

Constructors and Destructors


A class constructor is a special member Sub of a class that is executed whenever we
create new objects of that class. A constructor has the name New and it does not have any return
type. Following program explains the concept of constructor –
Class Line
Private length As Double ' Length of a line
Public Sub New() 'constructor
Console.WriteLine("Object is being created")
End Sub

Public Sub setLength(ByVal len As Double)


length = len
End Sub

Public Function getLength() As Double


Return length
End Function
Shared Sub Main()
Dim line As Line = New Line()
'set line length
line.setLength(6.0)
Console.WriteLine("Length of line : {0}", line.getLength())
Console.ReadKey()
End Sub
End Class

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

Public Radius As Integer

Public Sub SetRadius(ByVal Radius As Integer)


Me.Radius = Radius
End Sub

Public Function Area() As Double


Return Me.Radius * Me.Radius * Math.PI
End Function

End Class
Sub Main()

Dim c As New Circle


c.SetRadius(5)

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

Consider a base class Shape and its derived class Rectangle –


' Base class
Class Shape
Protected width As Integer
Protected height As Integer
Public Sub setWidth(ByVal w As Integer)
width = w
End Sub
Public Sub setHeight(ByVal h As
Integer) height = h End Sub
End Class
' Derived class
Class Rectangle : Inherits Shape
Public Function getArea() As Integer
Return (width * height)
End Function
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.

Overloading, Overriding, and Shadowing


Overloading, overriding, and shadowing are also important concepts in Visual Basic
OOP. These techniques allow you to create multiple members with the same name.

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:

Public Class ImplementationClass1 Implements Interface1


Sub Sub1(ByVal i As Integer) Implements Interface1.Sub1 '
Place code here to implement this method.
End Sub
End Class

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

Private Radius As Integer


Sub New(ByVal x As Integer, ByVal y As Integer, _
ByVal r As Integer)
Me.x = x
Me.y = y
Me.Radius = r
End Sub
Public Overrides Function Area() As Double
Return Me.Radius * Me.Radius * Math.PI
End Function
Public Overrides Function ToString() As String
Return String.Format("Circle, at x: {0}, y: {1}, radius: {2}", _
Me.x, Me.y, Me.Radius)
End Function
End Class
Sub Main()
Dim c as New Circle(12, 45, 22)
Console.WriteLine(c)
Console.WriteLine("Area of circle: {0}", c.Area())
Console.WriteLine(c.GetCoordinates())
End Sub
End Module

You might also like