PGDCA-II Programming in VB - Net Compiled by Prafulla Sir
PGDCA-II Programming in VB - Net Compiled by Prafulla Sir
Windows form, working with Visual Studio IDE, creating a .NET solution, MDI
application, components and controls, Data types, variables, Type conversions, operators,
Methods and events, Scope and life time of variables, Creating Enumertions.
GUI Programming with window forms, Showing & hiding forms, Textbox, RichText
box, Label, Button, Listox, Comboboxes, Checkbox, Picturebox, Radio button, Toggle
Button, Panel, Groupbox, Scrollbar, Timer, Dialog boxes, OpenFile Dialog, SaveFile dialog,
Print dialog, Font dialog, Color dialog, Designing menus and sub menus.
ADO .NET Architecture, NET data provider, dataset components, creating database
applications using Windows forms (Database connectivity through ADO .NET), Accessing
data using server explorer, Data Adapters & Data sets, Command & Data reader, data bind
control, displaying data in data grid.
Books Recommended
Note: - The thing to note here is that .NET is not a language but it is a software and
language neutral platform.
FCL is a standard library of Microsoft and is a library of reusable classes, interfaces and
value types.It is used to develop web-based, Windows GUI applications and ASP.NET
applications.
.NET languages
The .NET Framework supports visual basic, C, C ++, C #, asp.net, Jscript.net, ADO.NET
and other .NET languages.
The second part of the Net Framework is the Common Language Runtime (CLR).CLR is
considered as the first layer of the dot net framework CLR defines the execution
environment of programs written in dot net ie CLR provides the user an environment under
which the user can easily create any application in the shortest time (Develop) can be
executed.
When you write applications for the .Net framework in these languages, such as VB.Net or C
#, your source-code is never directly compiled into machine code.
Instead, the C # compiler in VB converts your code into a special language called MSIL
(Microsoft Intermediate Language).
MSIL is largely an object-oriented assembly language. But like an assembly language, it
does not depend on every CPU. It is a low-level and platform-independent language.
When your application is executed, the MSIL code is compiled into "just-in-time" machine
code.JITTER (the just-in-time compiler) does this work.
Generally, your entire application is not compiled in machine code. Instead, only the called
method is compiled.
Actually .Net Framework understands only one language MSIL. But you can use VB.Net and
C # languagesto write applications, because compilers included in the .Net framework help
you compile code written in these languages into MSIL.
You can use the following languages for the .Net Framework -
Fortran PHP
JavaScript Python
CTS (Common Type System) is provided by CLR, which provides a secure environment for
running the program. CLR is also known as CLI (Common Language Infrastructure).
When the dot net program is compiled, the output of the program is not an execution file but
a file that contains a special type of code called Microsoft Intermediate Language MSIL.
The CLR converts this intermediate code into executable code when the program is
executed.
JIT Compiler converts MSIL into native code as required.
The CLR is mainly divided into five parts, which are as follows -
Ans. Common type system (CTS)In the dot net framework, CTS (Common type system)
specifies the type systems
represented in computer memory
and their values
It helps to share information
between programs written in
different languages.
It supports Cross language
platform, due to which it helps in sharing information between programs written in different
language, it supports and fully implement an Object oriented model.
It is used to share objects of different languages on the same platform.
Example: - C # program can be used with the program of Visual Basic. It defines the rules
for sharing information between objects. It provides interaction between data types of
different languages. Thus CTS plays an important role in dot net.
Ans.
Ans. AssembliesA logical group of one or more files in a dot net is called an assembly.
An Assemble is a collection of a single DLL (Dynamic Link Library) or EXE files.
In dot net assemblies, it is possible to retain many versions of a particular assembly.
Each assembly has a Manifest and Compile Code. Dot net assemblies are full Self
Describing. It is an important part of the dot net framework. It incorporates many types of
information to run the program, as well as it does the following.
This includes the codes run by the CLR. Code of Microsoft Intermediate Language
cannot be executed without assembly. It forms an Associated Assembly.
This defines the Security Limitations of the program. It processes the Request and
Permission to execute the program.
This creates Type Limitations. All identified types are stored in the assembly.
Ans. Class Library-The Microsoft Base Class Library is the most important part of the .Net
Framework. This is a library that can be used by all computer languages of dot net. It
provides common library for all. There are many common functions, methods and classes in
this library which are common for all dot net languages. These functions and methods are
used for various tasks.
Example: - File reading and writing, database interaction, XML documentation etc.
Following are some important .Net Library Classes and Namespaces.
System.Data: This database provides related functions and methods. Also known as
ADO.Net.
System.Windows: This class is used for all Windows Operating System related
Functions and Methods.
System. Windows. Forms: It is used for all Controls, Methods and Functions of
Windows Forms.
Ans. Code Execution Process- The Code Execution Process involves the following two
stages:
1. Compiler time
process.
2. Runtime process.
2. Runtime process.
1. The Common Language Runtime (CLR) includes a JIT compiler for converting MSIL
to native code.
2. The JIT Compiler in CLR converts the MSIL code into native machine code that is
then executed by the OS.
3. During the runtime of a program the "Just in Time" (JIT) compiler of the Common
Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate
Language (MSIL) into native code.
BYTE CODE (MSIL + META DATA) ----- Just-In-Time (JIT) compiler------> NATIVE CODE
Ans. .Net Namespace provides the fundamental unit of logical code grouping while an
assembly provides a fundamental unit of physical code grouping.
Namespace
Namespaces is a logical group of related classes that can be used by any other language
targeting the Microsoft .Net framework. It is more used for logical organization of your
classes. Namespaces are a way of grouping type names and reducing the chance of name
collisions.
The fully qualified name of a class is constructed by concatenating the names of all the
namespaces that contain the type. For example, the fully qualified name of the TextBox
class is System.Windows.Forms.TextBox. That means TextBox class is contained in the
Forms namespace that is contained in the Windows namespace that is contained in the root
System namespace.
Assembly
An assembly is a collection of types and resources that are built to work together and form a
logical unit of functionality. It is an Output Unit, that is .exe or .dll file. It is a unit of
Deployment and a unit of versioning and also it contains MSIL (Microsoft Intermediate
Language) code. Assemblies are self-describing, it contains all the metadata about the
modules, types, and other elements in the form of a manifest.
Assemblies are of two types: Private and Shared Assemblies.
Private Assemblies
Private assembly is intended only for one application. The files of that assembly must be
placed in the same folder of the application.
Shared Assemblies
Shared assembly is to be made into a Shared Assembly, then the naming conventions are
very strict since it has to be unique across the entire system
Ans. GC.Collect()Memory management is a primary thing for any application. The .Net
Framework provides a new mechanism for releasing unreferenced objects from the memory,
this process is called Garbage Collection (GC). In some rare situations, forcing a Garbage
Collection may improve your application's performance. The garbage collection (GC)class
provides a GC.Collect method, which you can use to give your application some direct
control over the garbage collector. It might be appropriate to use the GC.Collect method in a
situation where there is a significant reduction in the amount of memory being used at a
defined point in your application's code.
GC.Collect call is discouraged because it decreases the current performance of the
application. Whenever you call the garbage collector to performs a collection, it suspends all
currently executing threads. This can become a performance issue if you call GC.Collect
more often than is necessary. You should be careful not to place code that calls GC.Collect
at a point in your program where users could call it frequently. However, if you can reliably
test your code to confirm that calling Collect () won't have a negative impact then go ahead.
It is not guaranteed that the Garbage Collection process will start after calling the method
and the memory is release. So, there is still uncertainty whether actually the Garbage
Collection will occur or not.
.Net Garbage Collection
The .Net Framework provides a new mechanism for releasing unreferenced objects from the
memory (that is we no longer needed that objects in the program) ,this process is called
Garbage Collection (GC).
When a program creates an Object, the Object takes up the memory. Later when the
program has no more references to that Object, the Object's memory becomes unreachable,
but it is not immediately freed.
The Garbage Collection checks to see if there are any Objects in the heap that are no longer
being used by the application. If such Objects exist, then the memory used by these Objects
can be reclaimed. So these unreferenced Objects should be removed from memory, then
the other new Objects you create can find a place in the Heap.
Finalization allows a resource to clean up after itself when it is being collected. This
releasing of unreferenced Objects is happening automatically in .Net languages by the
Garbage Collector (GC). The programming languages like C++, programmers are
responsible for allocating memory for Objects they created in the application and reclaiming
the memory when that Object is no longer needed for the program. In .Net languages there
is a facility that we can call Garbage Collector (GC) explicitly in the program by calling
System.GC.Collect.
Garbage collector of .NET tries to compact the memory in such a way as to increase the
working space required for heap. The class GC of .NET class library controls the garbage
collector. The core task of performing a collection is executed by the GC’s optimizing engine
that determines the best time to perform collection based on allocations being made. GC
runs are non-deterministic since the call to GC cannot be guaranteed. However, explicit calls
to the overloaded 'Collect()' method of the class GC can be used whenever needed.
The advantages that GC provides include:
clearing up of memory of reclaimed objects that are no longer in use (which helps to
initialize managed objects allocated in future and provision of memory safety of
objects to avoid an object using content of another.)
Unit II
Programming with .NET Framework
Name: form is used to identify the form when writing name codes. It can only be
changed at design time.
Msgbox (Me.Name)
Text: It is used to get or set the title to be displayed in the title bar of the property
form.
AcceptButton: This property is used to set the default of any button available in the
form, which automatically clicks on pressing the ENTER key.
Me.AcceptButton = Button1
CancelButton: This property is used to default set any button available in the form,
which automatically clicks on pressing Esc key.
Me.AcceptButton = Button2
AutoScroll: When this property is ture, the size of the form is less than available
controls to automatically display the scrollbar.
Me.AutoScroll = True
BorderStyle: This property is used to set the border style of the form. It has the
following values:
ControlBox: This property is used to display or hide the control box (Maximize,
Minimize and close button). It will be displayed when it is true and hide if it is false.
Minimum Size / Maximum Size: This property is used to set the minimum size and
maximum size of the form. It has two sub properties height and width.
Size: This property is used to get or set the size of the form. It has two sub-properties
height and width.
StartupPosition: It is used to set the initial position when the form is run.
BackgroundImage: This is done to set or get the image in the background of the
form.
Releasing
Version Release with
date
14. From the Type of Project displayed in this window, we select the project that we
want to create. Some of these project types are Visual Basic Projects, Visual C ++
Projects, Visual C # Projects, etc. Each of these project types has different
applications; For example, from Visual Basic Project Type we can create Window
Application, Console Application etc.
15. In this window we will design the form according to our requirement.
Visual Basic Dot Net projects have different types of Templates, which are as follows –
Properties Window
The Visual Basic IDE (Visual Studio) provides the following components.
Form Designer
Menu Bar
1. File:File Menu provides facility to create new project, save and open project, add
project, etc.
16. Edit: It provides Basic Editing Tools. Such as Cut, Copy, Paste, Find, Replace,
Undo, Redo, Delete etc.
17. View: This Contains the Commands of Displaying Menu IDE to Windows. Such as
Solution Explorer, Designer, Code Window etc.
18. Project: This gives the command to add new items to the Menu Project.
19. Build: This gives the command to build the Menu Project.
20. Debug: This gives the command for menu debugging.
21. Data: It does the Command Container associated with the Menu Database.
22. Tool: Contains Extra Tools of Menu.Net. Such as Connect To Server, Connect To
Device etc.
23. Window: This Contains Window Arrangement Command like Tile, Cascade etc.
24. Help: Contains the command associated with Help. This menu has the facility of
Online and Offline Help.
Toolbar
SolutionExplorer
Toolbox
Form Designer
Properties Window
After these Buttons the Properties Window is divided into 3 parts. Which are as follows.
Code Window
Object Browser occupies an important place in Visual Studio. It uses components used in
.Net such as Classes, Namespaces, Enumerators, Interfaces Etc. Shows the. Object
Browser is used to view the properties, events and methods of .Net classes. The Object
Browser or Ctrl + W + J Shortcut Key is used in the View menu to make it appear in the IDE.
On top of this, there is a facility to search for objects. It is mainly divided into three parts.
1. Object Pan: This pan contains a hierarchical list of .Net's Namespaces, Interfaces
and Classes that can be explored. When you explore it, you get a list of classes.
2. Member Pan: In this Pan, the list of members of the class selected in
Object Pan appears. Which mainly consists of properties, events and
methods that can be selected.
3. Description Pan: This Pan contains the description of the selected object
or its member in the Member and Object Pan.
Output Window
The Output Window is also a window of the Visual Studio IDE that displays the messages
generated when programs are compiled and run. In this, the messages are generated when
the program is Build and Run. To show it in the IDE, use the Output Window or Ctrl + W + O
Shortcut key in the View menu. It has a toolbar which contains tools to view messages.
Like- Search, Next, Previous etc. After this all the message displays are in a box.
Ans. variable, its value can be changed by the program at runtime. The accessibility or the
scope of a variable refers to where the variable can be read from or written to, and its
lifetime, or how long it stays in the computer memory.e.g. int i;
Constant
A Constant is something that will always remain the same though out the entire lifetime of a
program. A Constant variable cannot be modified after it defines and it cannot be change
throughout the program. The Constant with a fixed value tells the compiler to prevent the
programmer from modifying it. Whenever you try to change it, it will throw an error message.
Constant variables declare with const keyword and can be used with primitive data types.
Constants are set at compile time itself and assigned for value types only. e.g. public const
double PI = 3.14159;
Static
Static variable is a property of a Class rather than the instance of class. It is stored on the
data segment area of memory and the same value is get shared to all instances of that
class. It can be assigned for reference types and set at run time. The static modifier can be
applied with classes, fields, methods, properties, operators, events and constructors. It
represents a kind of a global value for all the instances of that class and can able to call
them using class name.
Product.price = 100;
Where Product is class name and price is a static declaration.
1. Variable name may consist of digits (0-9), Alphabets (A-Z, a-z) and underscore
symbol.
2. Variable name can not contain any special symbols.
3. Reserved words or key words can not be used as a name of variable.
4. The length of variable must not exceed 255 characters.
5. Variable name can not start with digit.
6. Uppercase and Lowercase letters are different.
Most of the programming languages force the programmer to declare all the variables before
they can be referenced in the program otherwise it will generate a compile time error.
However VB.NET does not forces the programmer to declare variables. It means there is no
need to declare the variables before using it in the program. Variables can be declared in
visual basic using two methods.
(1) Implicit Declaration
(2) Explicit Declaration
By default VB.NET supports explicit variable declaration. However if you wish you can
change default behavior by following steps given below:
Step 1: Select Properties option from Project Menu.
Step 2: Select Compile Option.
Step 3: Select OFF in the Option Explicit Combo Box.
You can also write Option Explicit OFF at starting of code window to turn OFF explicit
variable declaration.
In VB.NET it is not compulsory to declare all the variables in advance before it can be
referenced in the program. You can use the variable directly when it is required. When the
compiler finds a variable that is not declared, it will automatically create a new variable of
type object. This type of technique is known as implicit declaration of variable.
The data type of variables declared using implicit declaration is object by default. You can
store any type of value in this type of variable, the compiler will automatically determines the
type of the variable depending upon the type of the value that is stored in the variable.
Disadvantage of Implicit Declaration:
(1) It will decrease the speed and efficiency of the program because the compiler does not
know in advance which variables are being used in the program and what are the data types
of those variables. The compiler has to allocate memory to every variable when it finds a
new variable.
(2) Typing errors can not be caught using this type of technique because if you make a
typing mistake while writing the name of the variable instead of generating a compile time
error the compiler will create a new variable.
(3) By default the data type of the variables declared using this technique is object which
occupies more memory as compared to specific data type.
By default in VB.NET it is compulsory to declare all the variables in advance before it can be
referenced in the program. You can also declare the variable explicitly before it is referenced
in the program. This type of technique is known as explicit declaration of variable.
Variables can be declared explicitly using the Dim statement. The general syntax for
declaring the variable is given below:
Syntax:
Dim variable-name as DataType
Example:
Dim Name as String
When you declare the variable the compiler allocates space for that variable depending upon
the Type of the variable and assigns one name for that reserved memory space. So later in
the program you can refer to that memory space using the name of the variable. We can
also declare more then one variables of the same type in the same line as shown below:
Dim a as integer, b as integer, c as integer
We can also declare more then one variable of different type in the same line as shown
below:
Dim a as Integer, b as String, c as Double
Ans. When a variable is declared, then we also have to write its data type, because the
value to be stored in any variable depends on its data type. The type of data type of the
variable will be the same type. Value store can be done.
DATATYPE in a programming language describes that what type of data a variable can
hold. When we declare a variable, we have to tell the compiler about what type of the data
the variable can hold or which data type the variable belongs to.
Syntax : Dim VariableName as DataType
VariableName : the variable we declare for hold the values.
DataType : The type of data that the variable can hold
In Programming, data types define the type of data. Data types tell the type of data to be
stored as well as its data storage length. The variables in Visual Basic are divided into the
following five categories.
Numeric
String
Boolean
Date
Object
1. Numeric Variables: Numbers in which decimal points are not used are called Integer
numbers. It consists of data types that store numbers. They are used to perform
mathematical operations. It contains the following data type’s-
• Short (Int16): It is used to store integer value. In this, the value can be stored from
-32768 to 32767 and it takes 2 bytes in memory.
Dim a as short
a = 10000
• Integer (Int32): It is used to store integer value. In this, the value can be stored
from -2147483648 to 2147483647 and it takes 4 bytes in memory.
Dim a as integer
a = 1000000
• Long (Int64): It is used to store integer value. It can store more value than integer
and it takes 8 bytes in memory.
Integer variables are stored sighned 32 bit integer values in the range of
-2,147,483,648 to +2,147,483,647
25. Floating point Numbers: Numbers in which decimal points are used, are called
floating point Numbers.
• Single: It stores single precision floating no. It can store values from
-3.402823E38 to -1.401298E-45 and 1.401298E-45 to 3.402823E38. It takes 4
byte memory.
• Double: It stores double precision floating no. It can store values from
-1.797693134486232E308 to -4.94065645841247E-324 and
4.94065645841247E-324 to 1.797693134486232E308. It takes 8 byte memory.
• Decimal: It can store 0 to 7.9228162514264337593543950335 positive and
negative values. It takes 16 Byte in memory.
• Byte: This is also a numeric data type that stores values from 0 to 255. It has 2
byte in memory
26. String: A group of characters is called a string. It is used to store characters. It
consists of the following 2 types.
• String: It is used only to store text. It stores the set of characters. It can store text
up to 2 GB.
• Char: It is used to store single character. And takes 2 byte space in memory.
String variables are stored any number of alphabetic, numerical, and special
characters . Its range from 0 to approximately 2 billion Unicode characters.
27. Boolean: This data type is used to store true or false value. It is mostly used
to check conditions.
Boolean variables are stored 16 bit numbers and it can hold only True or false.
28. Date: This data type is used to store date and time. In this, use # character to
store the date or time.
Dim a as date
a = # 1/4/2005 #
29. Object: This is a common data type that is used to store all types of values with
common features of all data types.
Ans. To process any type of data, we have to first decide what kind of data we want to store
in the memory of the computer, because as long as we store the data to be processed in the
computer's memory If we do not, we cannot process that data.
Since different types of data reserve space of different sizes in memory, when we get to
know the type of data to be processed, then we will be in memory based on the keyword
representing that data type. Some reserve the space and assign a name to that space. This
name is a Symbolic Identifier of the Reserved Memory Location, which is determined based
on the rules of the Identifier Naming Convention.
To store a data based on the need of the program, the process of reserving space in the
memory of the computer and giving a symbolic name of that space is called Identifier
Declaration.
If the value of the identifier to be defined remains constant throughout the program, this
process is called Constant Declaration, whereas if the value of the identifier to be defined
changes from time to time across the program depending on the need of the program, it
Variable Declaration says.
Variables hold a very important place in computer programming. Variables, named locations
that are used to store a value. Each variable has a name and value as well as a Type. There
are many types of data types in visual basic. Such as - Integer, String, Date, Char, Decimal
etc.
Type Example
Integral types SByte, Byte, Short, UShort, Integer, UInteger, Long, ULong and Char
VB.Net also allows defining other value types of variable like Enum and reference types of
variables like Class.
Declaring Variables
In Visual Basic.Net, the dim statement is used to declare the variable. The following are
Syntax.
Syntax: Dim <Variable Name> As <Data Type>
Example: Dim name As String
In this statement Dim states the dimension of the keyword variable, variable name, variable
name, As keyword and data type. In Visual Basic.Net, variables are usually declared this
way. Also the variable declaration statement changes according to the scope. The public
keyword is used in place of Dim to declare the public variable.
Similarly, private and friend keywords are also used to declare variables. private, public,
protected and friend variable are used to scope. Multiple variables can be declared in a
single statement in VB.Net. Example: Dim a, b, c as Integer
Similarly, multiple type variables can also be declared in a single dim statement. Example:
Dim a As Integer, name As String, b As Boolean
No other character is used except for numbers and underscore in variable name.
The process of changing a value from one data type to another type is called conversion.
Conversions are either widening or narrowing, depending on the data capacities of the types
involved. They are also implicit or explicit, depending on the syntax in the source code.
Widening and Narrowing Conversions
An important consideration with a type conversion is whether the result of the conversion is
within the range of the destination data type.
A widening conversion changes a value to a data type that can allow for any possible value
of the original data. Widening conversions preserve the source value but can change its
representation. This occurs if you convert from an integral type to Decimal, or
from Char to String. For example, converting a value of type integer to a value of type Long
is a widening conversion because the Long type can accommodate every possible value of
the Integer type. Widening conversions always succeed at run time and never incur data
loss. You can always perform them implicitly, whether the Option Strict Statement sets the
type checking switch to On or to Off.
Narrowing Conversions
A narrowing conversion changes a value to a data type that might not be able to hold some
of the possible values. For example, a fractional value is rounded when it is converted to an
integral type, and a numeric type being converted to Boolean is reduced to
either True or False.
The reverse directions of the widening conversions in the preceding table (except
that every type widens to itself)
Narrowing conversions do not always succeed at run time, and can fail or incur data loss. An
error occurs if the destination data type cannot receive the value being converted. For
example, a numeric conversion can result in an overflow. The compiler does not allow you to
perform narrowing conversions implicitly unless the Option Strict Statement sets the type
checking switch to Off.
An implicit conversion does not require any special syntax in the source code. In the
following example, Visual Basic implicitly converts the value of k to a single-precision
floating-point value before assigning it to q.
Dim k As Integer
Dim q As Double
' Integer widens to Double, so you can do this with Option Strict On.
k = 432
q = k
An explicit conversion uses a type conversion keyword. Visual Basic provides several such
keywords, which coerce an expression in parentheses to the desired data type. These
keywords act like functions, but the compiler generates the code inline, so execution is
slightly faster than with a function call.
In the following extension of the preceding example, the CInt keyword converts the value
of q back to an integer before assigning it to k.
q = Math.Sqrt(q)
k = CInt(q)
Ans. An operator refers to a symbol that instructs the compiler to perform a specific logical
or mathematical manipulation. The operator performs the operation on the provided
operands. Microsoft VB.Net comes with various types of operators.
Arithmetic Operators
You can use arithmetic operators to perform various mathematical operations in VB.NET.
They include:
Symbol Description
Comparison Operators
These operators are used for making comparisons between variables. They include the
following:
> for checking whether the value of the left operand is less
than that of the right operand. If yes, the condition will
become true.
<= for checking whether the value of the left operand is less
than or equal to that of the right operand. If yes, the
condition will become true.
Logical/Bitwise Operators
These operators are used for performing shift operations on binary values.
Xor The Binary XOR Operator. For copying a bit if set in one of
the operands rather than both.
Assignment Operators
Miscellaneous Operators
Ans.One of the very prime features of the visual basic language is that it makes use of the
statements which is used to specify actions. Even when you visualize a visual studio project
as procedural series which are executed in a sequence but in reality, they all form a part of
the events and therefore they are event-driven which means that the flow of execution is
only determined by all the external occurrences happening around which are also called as
events. They are basically user actions such as keypress, mouse-related movements, clicks,
etc. or it is also used for doing some occurrences such as system-oriented and generated
notifications. Also, the applications are also required to respond to all the events whenever
they occur. This includes clicking on a home button or entering some form of a text in the
text box, clicking on the menu item. They all form part of event examples. An event can be
defined to be an action which calls another function or causes another event to get triggered.
Handlers, on the other hand, are functions that tell us how to respond to the event.
Below are the Two types of VB. Net event:
1. Mouse-Based Events
Mouse events occur when the mouse makes any movement in controls or the forms. The
following are some of the mouse-related events which are related to a control class.
1. MouseEnter:This event gets triggered when the pointer of the mouse enters the control.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)Handles
object.MouseEnterProgram BodyEnd Sub
Example:
//defining a subroutinePrivate Sub MouseEnter(sender As ObjectType, e As
EventArguments)Handles abc.MouseEnter//writes the code for handling mouse enter on abc
textboxabc.BackColor = Color.Blueabc.ForeColor = Color.RedEnd Sub
Popular Course in this category
2.MouseDown: This event gets triggered when the mouse button is pressed and the cursor
is brought towards the downside of it.
Syntax:
private sub func_name(alias as Datatype1, alias as Datatype2)
Handles object.MouseDown
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseDown(sender As ObjectType, e As EventArguments)
Handles abc.MouseDown
//writes the code for handling mouse down
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
3.MouseUp: This event gets triggered when the mouse pointer is over the control which is
handling it and the already pressed mouse button is released.
Syntax:
private sub func_name(alias as Datatype1, alias as atatype2)
Handles object.MouseUp
Program Body
End Sub
Example:
//defining a subroutine
Private Sub MouseUp(sender As ObjectType, e As EventArguments)
Handles abc.MouseUp
//writes the code for handling mouseUp
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
4.MouseLeave: This is the event that gets triggered 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
Example:
//defining a subroutine
Private Sub MouseLeave(sender As ObjectType, e As EventArguments)
Handles abc.MouseLeave
//writes the code for handling mouseLeave for abc textbox
abc.BackColor = Color.Blue
abc.ForeColor = Color.Red
End Sub
5. MouseWheel: This event gets triggered when the wheel of the mouse moves and the
control is provided the focus.
Syntax
<element onwheel="mytestScript">
object.onwheel = function(){mytestScript}; object.addEventListener("wheel", mytestScript);
Example:
document.getElementById("DIV").addEventListener("wheel", testFunction);
function testFunction() {this.style.fontSize = "70px";}
Methods
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.
EndSub
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
The difference between lifetime and scope is quite simple. Lifetime - Refers to how long or
when the variable is valid (i.e. how long will it retain its value for).
Scope - Refers to where the variable can be accessed.The difference between lifetime and
scope is quite simple.lifetime is how long the variable retains its value for.The scope refers to
where the variable can be used.
Variable Lifetime
The lifetime of the local variable "imylocal" extends from the moment ProcedureOne is
entered to the moment ProcedureOne has finished. However, the local variable "imylocal"
still exists when ProcedureTwo is called, it is just out of scope.
Variable Scope
Every variable has a scope associated with it. This scope refers to the area of code where
the variables will be recognised. Variables (and constants) have a defined scope within the
program. The scope for a variable can either be: Procedure Level - Also known as a local
variable. Module Level - A private module level variable is visible to only the module it is
declared in. Global Level - A public module level variable is visible to all modules in the
project.
A Variable’s Scope: The scope of a variable is the section of the application that can see
and manipulate the variable. If a variable is declared within a procedure, only the code in the
specific procedure has access to that variable. When the variable’s scope is limited to a
procedure it’s called local.
e.g.
Private Sub Command1_Click()
Dim i as Integer
Dim Sum as Integer
For i=0 to 100 Step 2
Sum = Sum +i
Next
MsgBox “ The Sum is “& Sum
End Sub
A variable whose value is available to all procedures within the same Form or Module are
called Form-wide or Module-wide and can be accessed from within all procedures in a
component. In some situations, the entire application must access a certain variable. Such
variable must be declared as Public.
Lifetime of a Variable: It is the period for which they retain their value. Variables declared
as Public exist for the lifetime of the application. Local variables, declared within procedures
with the Dim or Private statement, live as long as the procedure.
You can force a local variable to preserve its value between procedure calls with the Static
keyword. The advantage of using static variables is that they help you minimize the number
of total variables in the application.
Variables declared in a Form outside any procedure take effect when the Form is loaded and
cease to exist when the Form is unloaded. If the Form is loaded again, its variables are
initialized, as if it’s being loaded for the first time.
An Enum type has a name, an underlying type, and a set of fields, each representing a
constant. The name must be a valid Visual Basic .NET qualifier. The underlying type must
be one of the integer types—Byte, Short, Long or Integer. Integer is the default.
Enumerations are always strongly typed and are not interchangeable with integer number
types.
Enumerations cannot have floating-point values. If an enumeration is assigned a floating-
point value with Option Strict On, a compiler error results. If Option Strict is Off, the
value is automatically converted to the Enum type.
To declare an enumeration
1. Write a declaration that includes a code access level, the Enum keyword, and a valid
name, as in the following examples, each of which declares a different Enum.
PrivateEnum SampleEnum
SampleMember
EndEnum
PublicEnum SampleEnum2
SampleMember
EndEnum
ProtectedEnum SampleEnum3
SampleMember
EndEnum
FriendEnum SampleEnum4
SampleMember
EndEnum
ProtectedFriendEnum SampleEnum5
SampleMember
EndEnum
30. Define the constants in the enumeration. By default, the first constant in an
enumeration is initialized to 0, and subsequent constants are initialized to a value of
one more than the previous constant. For example, the following enumeration, Days,
contains a constant named Sunday with the value 0, a constant named Monday with
the value 1, a constant named Tuesday with the value of 2, and so on.
PublicEnum Days
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
EndEnum
31. You can explicitly assign values to constants in an enumeration by using an
assignment statement. You can assign any integer value, including negative
numbers. For example, you may want constants with values less than zero to
represent error conditions. In the following enumeration, the constant Invalid is
explicitly assigned the value –1, and the constant Sunday is assigned the value 0.
Because it is the first constant in the enumeration, Saturday is also initialized to the
value 0. The value of Monday is 1 (one more than the value of Sunday); the value
of Tuesday is 2, and so on.
PublicEnum WorkDays
Saturday
Sunday = 0
Monday
Tuesday
Wednesday
Thursday
Friday
Invalid = -1
EndEnum
Specify the type of the enum by using the As clause, as shown in the following
example.
Ans. Control structures enable programmers to control the order of events in their programs.
Visual Basic's sequence, selection and repetition structures are used to select and repeat
various statements and thereby execute complex algorithms. In the process, we introduce
commonly used shorthand operators that allow the programmer quickly to calculate and
assign new values to variables. Normally, statements in a program are executed one after
another in the order in which they are written. This process is called sequential execution.
However, various Visual Basic statements enable the programmer to specify that the next
statement to be executed might not be the next one in sequence. A transfer of control occurs
when a statement other than the next one in the program executes.
Visual Basic provides seven types of repetition structures: While, DoWhile/Loop,
Do/LoopWhile, DoUntil/Loop, Do/LoopUntil, For/Next and ForEach/Next. (ForEach/Next is
covered in Chapter The control flow in VB.Net controls the flow of statements program. It
controls the data used in the program. These statements are of two types.
The words If, Then, Else, End, Select, Case, While, Do, Until, Loop, For, Next and Each are
all Visual Basic keywords.
Conditional Statements
Looping Statements
The if-then statement is used to check normal conditions. If the condition written in it is
true, the statements of If- End If block are executed. And the control goes out when the
condition is false.
Syntax:
If Condition Then
Statements
End If
Example:
If a> b Then
Msgbox ("A is greater")
End If
This conditional statement consists of two blocks. An If block is executed when the
condition is true and an Else block is executed when the condition is false.
Syntax:
If Condition Then
[If block states]
Else
[Else Block Statements]
End If
Example:
If a> b Then
Msgbox ("A is greater")
Else
Msgbox ("B is greater")
End If
Select case
The Select Case statement is used to check the value of an expression on different
cases. In this, the expression written in select case is matched with value cases and if
the correct match is found, the statement of that block is executed. If a case does not
match, the case Else statement is executed.
Syntax:
Select Case textexpression
Case ExpressionList ……… N
[‘Statements…… N]]
[Case Else
[Statement Else]]
End select
Example:
Select Case Now.DayOfWeek
Case DayOfWeek.Sunday
MsgBox ("Its Time to Enjoy")
Case DayOfWeek.Monday
MsgBox ("Have a nice week")
Case else
MsgBox ("Enjoy this week")
End select
Select case
Looping statements are used to repeat a code or task multiple times. These statements
repeatedly repeat the task according to a condition. There are mainly three types of looping
statements in VB.Net.
• For-Next
• While- End While
• Do- Loop
For-next
It is used to run the loop according to the loop condition. In this loop, a condition is
defined by which looping statements are executed when true and it is exited directly
when false. Following is its syntax.
Syntax:
While Condition
[Statements]
[Exit while]
[Statements]
End While
Exit while is used to break the while loop.
Example:
Dim i As Integer = 0
While i <= 10
MsgBox (i)
End While
Do-loop
It is similar to loop while loop. It is used to repeat a statement for indefinite time. do
loop executes the statement until the condition written in while or until becomes false.
In this, two keywords while and until are used. It has an exit do statement which is
used to break the loop in between. Following is the syntax of this loop.
Syntax:
Do {[While / until] condition}
[Statements]
[Exit Do]
[Statements]
Loop {[While / until] condition}
Ans. When we have to access and manipulate a program by storing a lot of data of the
same type, then instead of declaring many Variables to store these same types of data, we
do Array Declare.
Array is a type of Reference Type that uses the Heap Area of Memory to store the same
type of Data Items and uses Continues Memory Locations to store every Data Item of Array.
All data items are stored in memory in a fixed order and a unique Zero Based Unique Index
Number is specified with each element to uniquely identify it. Also, Array is a Fixed Data
Structure. So once the Array's size is defined, then the Array's size cannot be modified.
Declaring Array: Array, like Simple Variable, is given the value of the last index of the array
in parentheses (parentheses) after the name of the array while Declare using Dim, Private or
Public Statement. Which is called subscript, index or size.
Syntax: Dim <array name> (subscript) As <Data Type>
Example: Dim employee_ name (20) As String
Dim salary (20) As Integer
Types of Array
There are two types of Array in Visual Basic.
1. One Dimensional Array
32. Multi-Dimensional Array
1.One Dimensional Array: An array containing only one index or subscript is called a
dimensional array. Multiple values can be stored in it. In this, its index is used to store or
access a value in an array.
Example: Dim marks (10) As Integer
The marks array can store 0 to 9 indexes or 10 values in the marks array.
• Initializing one dimensional Array: values can be inserted in both the design and run time in
a dimensional array.
Array index or Curly brackets {} are used to store the value in design time.
Syntax: Dim array_name () As DataType = {element1, element2,….}
Example: Dim name () As String = {"Raj", "Shyam", "Ashu"}
or
Dim Name (2) As String
Name (0) = "Raj"
Name (1) = "Shyam"
Name (2) = "Ashu"
2. Multi-Dimensional Array: Arrays of many dimensions can be created in VB.Net. Arrays
that contain more than one subscripts are called multi-dimensional arrays. Dim, private or
public statements are also used to declare multi-Dimensional arrays. When declare it more
than one subscripts are given in it. It can store values equal to multiple of subscripts such
that n (2,3) array can store 6 values.
• Syntax: Dim <array name> (script1, script2…) As <Data Type>
• Example: Dim matrix (3, 3) as Integer
Dim T (2, 3, 4, 2) As Double
• Initializing Multi-Dimensional Array: Use Curly brackets to initialize Multi-Dimensional
Array.
Dim n (3, 3) As Integer = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
In visual basic, Method is a separate code block and that will contain a series of statements
to perform particular operations.
Ans. Generally, in visual basic Methods are useful to improve the code reusability by
reducing the code duplication. Suppose, if we have the same functionality to perform in
multiple places, then we can create one method with required functionality and use it
wherever it is required in the application.A method is a unit of functionality, an operation,
within a class or an object. Programs comprise multiple methods, organized in objects, and
accordingly combined to solve a particular problem. As any dictionary will tell you, a method
is simply a way of doing something. In OOP, methods are the way we do things with
procedures and functions.
You can think of the term routine as a noun used to refer collectively to procedures and
functions in structure−oriented languages like generic Pascal and BASIC, while method is
the collective noun in OOP.
Procedures are known as Sub methods in Visual Basic (short for subroutine) and do not
return a value. To return a value, you use a Function method. Both method types,
respectively, are demonstrated as follows:
'A Sub method
Sub MyMethod()
'Make hay . . .
End Sub
'A Function method
Function MyMethod()As Integer
'Make hay and return the amount made
Return amount 'or
Return MyMethod 'or
MyMethod = Amount
End Sub
Syntax of Visual Basic Methods
Parameter Description
Parameters The method parameters are useful to send or receive a data from
method and these are enclosed within parentheses and are
separated by commas. In case, if no parameters are required for a
method then, we need to define a method with empty parentheses.
Return_Type It is useful to specify the type of value the method can return.
Ans. Methods typically need to be provided with data (values or references to values) to
process when they are called or contacted. They can get this data from four places:
Class−level global data, or data the method can see elsewhere in the class
Data passed to a method via its parameter list. Parameter fields expose data to the
method.
Class−level data is data stored in the variable and constant fields, or within properties, which
are scoped to the class. The following code shows a simple method accessing class−level
data:
Public Class Calcs
Const C As Integer = 186355 'mps
Dim warp As Integer = 5
Public Function FactorLightSpeed() As Integer
Return C \ warp
End Function
End Class
Data from external objects or classes is data that is explicitly made available to calling
methods. Such data is usually provided from properties, fields, or return values from
methods that exist in an object with which the calling method is associated. In the following
example, the calling method uses the data received from a specialist object to continue with
its calculations:
Public Class Calcs
Const C As Integer = 186355 'mps
Public Function FactorLightSpeed() As Integer
Method−level data is data in variable or constant fields that is scoped local to the method or
any block nested inside the method. Such data is the most encapsulated data in an object
because only the method in which the variables or constants are declared has direct access
to the data. The following example shows variables and constants declared inside the
method:
Public Class Calcs
Const C As Integer = 186355 'mps
Public Function FactorLightSpeed() As Integer
Const C As Integer = 186355 'mps
Dim warp As Integer = 5
Return C \ warp
End Function
End Class
Visual Basic allows you to declare method−level static variables that have values that
survive the termination of the method. In other words, the static variable is not disposed of
with the destruction of the method call that comes after its completion. In the following
example, a static method retains its value after the execution steps exit the method:
Public Class Complex
Public Function FactorLightSpeed() As Integer
Const C As Integer = 186355 'mps
Static warp As Long = 5
Return C \ warp
End Function
End Class
The ability to pass data to a method in this fashion is the most powerful option you have for
making data available to the method. It is also the most dynamic, soft−coded way. The caller
or sender of the message maintains the utmost control over the data that is sent as an
argument to the method's parameter. The method is also able to tightly control the data that
it receives, because it can perform checks on the inbound references or values and take action
accordingly. It can perform such checks in a number of ways, which includes specifying the type
required, a built−in strong typing filter. The level of method coupling varies in the previous four key
options for providing data to the method. The highest level of coupling between methods results from
the class level or global variables, while the lowest level of coupling is achieved when data is
explicitly sent to the method via its formal parameter list.
Ans.A procedure is a group of statements that together perform a task when called. After the
procedure is executed, the control returns to the statement calling the procedure. VB.Net
has two types of procedures −
Functions
Defining a Function
The Function statement is used to declare the name, parameter and the body of a function.
The syntax for the Function statement is −
[Modifiers] Function FunctionName [(ParameterList)] As ReturnType
[Statements]
End Function
Where,
Modifiers − specify the access level of the function; possible values are: Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
FunctionName − indicates the name of the function
ParameterList − specifies the list of the parameters
ReturnType − specifies the data type of the variable the function returns
Example
Following code snippet shows a function FindMax that takes two integer values and returns
the larger of the two.
In VB.Net, a function can return a value to the calling code in two ways −
Module myfunctions
FunctionFindMax(ByVal num1 AsInteger,ByVal num2 AsInteger)AsInteger
' local variable declaration */
Dim result As Integer
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Max value is : 200
Recursive Function
A function can call itself. This is known as recursion. Following is an example that calculates
factorial for a given number using a recursive function −
Module myfunctions
Function factorial(ByVal num AsInteger)AsInteger
' 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()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Param Arrays
At times, while declaring a function or sub procedure, you are not sure of the number of
arguments passed as a parameter. VB.Net param arrays (or parameter arrays) come into
help at these times.
The following example demonstrates this −
Module myparamfunc
FunctionAddElements(ParamArray arr AsInteger())AsInteger
Dim sum AsInteger=0
Dim i AsInteger=0
ForEach i In arr
sum += i
Next i
Return sum
EndFunction
SubMain()
Dim sum AsInteger
sum =AddElements(512,720,250,567,889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
The sum is: 2938
You can pass an array as a function argument in VB.Net. The following example
demonstrates this −
Module arrayParameter
Function getAverage(ByVal arr AsInteger(),ByVal size AsInteger)AsDouble
'local variables
Dim i As Integer
Dim avg As Double
Dim sum As Integer = 0
For i = 0 To size - 1
sum += arr(i)
Next i
avg = sum / size
Return avg
End Function
Sub Main()
' an int array with5 elements '
Dim balance As Integer() = {1000, 2, 3, 17, 50}
Dim avg As Double
'pass pointer to the array as an argument
avg = getAverage(balance,5)
' output the returned value '
Console.WriteLine("Average value is: {0} ", avg)
Console.ReadLine()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Average value is: 214.4
Sub-procedure
Sub procedures are procedures that do not return any value. We have been using the Sub
procedure Main in all our examples. We have been writing console applications so far in
these tutorials. When these applications start, the control goes to the Main Sub procedure,
and it in turn, runs any other statements constituting the body of the program.
Defining Sub Procedures
The Sub statement is used to declare the name, parameter and the body of a sub
procedure. The syntax for the Sub statement is −
[Modifiers] Sub SubName [(ParameterList)]
[Statements]
End Sub
Where,
Modifiers − specify the access level of the procedure; possible values are - Public, Private,
Protected, Friend, Protected Friend and information regarding overloading, overriding,
sharing, and shadowing.
SubName − indicates the name of the Sub
ParameterList − specifies the list of the parameters
Example
Module mysub
SubCalculatePay(ByRef hours AsDouble,ByRef wage AsDecimal)
'local variable declaration
Dim pay As Double
pay = hours * wage
Console.WriteLine("Total Pay: {0:C}", pay)
End Sub
Sub Main()
'calling the CalculatePaySubProcedure
CalculatePay(25,10)
CalculatePay(40,20)
CalculatePay(30,27.5)
Console.ReadLine()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Total Pay: $250.00
Total Pay: $800.00
Total Pay: $825.00
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. The following
example demonstrates the concept −
Module paramByval
Sub swap(ByVal x AsInteger,ByVal y AsInteger)
Dim temp AsInteger
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 AsInteger=100
Dim b AsInteger=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()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
It shows that there is no change in the values though they had been changed inside the
function.
Module paramByref
Sub swap(ByRef x AsInteger,ByRef y AsInteger)
Dim temp AsInteger
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 AsInteger=100
Dim b AsInteger=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()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Before swap, value of a : 100
Before swap, value of b : 200
After swap, value of a : 200
After swap, value of b : 100
Ans. The show method of MessageBox is used to display User Specific message in a Dialog
Box and waits for the user to click a button. It returns an integer value indicating which
button is click by user. MessageBox is shown in the figure below:
1. Text is a compulsory argument. The String that you specify as a Text will display as
a message in the Dialog Box.
33. Caption is a compulsory argument. The String that you specified as a caption will be
display in the title bar of the Dialog Box.
34. Buttons is used to specify type of buttons to display in the message box.
35. Icon is used to specify type of icon to display in the message box.
Design a simple application that displays a message box when user clicks on Close Form
Button. If user clicks yes then form will be closed otherwise it remains open.
Step 1: Design a form as shown below:
Step 2: Now set properties of various controls as given below:
InputBox function display a prompt in the form of dialog box as shown below and waits for
the user to input some value in textbox or click a button.
If user clicks on OK button then it will return content of textbox in the form of string. If user
clicks on Cancel Button then it will return a blank value.
InputBox (Prompt As String,[Title As String=""], [DefaultResponse As String=""], [XPos As Integer
= -1], [YPos As integer = -1] ) As String
Here,
1. Prompt is a compulsory argument. The String that you specify as a Prompt will
display as a message in the InputBox Dialog.
36. Title is an optional Argument. The String that you specify as a Title will display in the
title bar of the InputBox. If you skip this argument then name of the application will
display in the title bar.
37. DefaultResponse is an Optional Argument. The String that you specify as a
DefaultResponse will display as a default value in the textbox of the InputBox. If you
skip this argument then Textbox of the InputBox is displayed empty.
38. XPos is an Optional Argument. It Specify the distance (in pixel) of the left edge of
the Input box from the left edge of the screen.
39. YPos is an Optional Argument. It Specify the distance (in pixel) of the upper edge of
the Input box from the top edge of the screen.
Design a simple application that ask user to enter name and display it in label using Input
Box Function.
Step 1: Design a form as shown below:
Q 9. What is an Exception?
Ans.An exception is a problem that arises during the execution of a program. An exception
is a response to an exceptional circumstance that arises while a program is running, such as
an attempt to divide by zero.
Exceptions provide a way to transfer control from one part of a program to another. VB.Net
exception handling is built upon four keywords - Try, Catch, Finally and Throw.
Try − A Try block identifies a block of code for which particular exceptions will be
activated. It's followed by one or more Catch blocks.
Finally − The Finally block is used to execute a given set of statements, whether an
exception is thrown or not thrown. For example, if you open a file, it must be closed
whether an exception is raised or not.
Throw − A program throws an exception when a problem shows up. This is done
using a Throw keyword.
Syntax
In the .Net Framework, exceptions are represented by classes. The exception classes in
.Net Framework are mainly directly or indirectly derived from the System.Exception class.
Some of the exception classes derived from the System.Exception class are
the System.ApplicationException and System.SystemException classes.
The System.ApplicationException class supports exceptions generated by application programs. So
the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class −
Ans. Handling Exceptions- VB.Net provides a structured solution to the exception handling
problems in the form of try and catch blocks. Using these blocks the core program
statements are separated from the error-handling statements.
These error handling blocks are implemented using the Try, Catch and Finally keywords.
Following is an example of throwing an exception when dividing by zero condition occurs −
Module exceptionProg
Sub division(ByVal num1 AsInteger,ByVal num2 AsInteger)
Dim result AsInteger
Try
result = num1 \ num2
Catch e AsDivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
EndTry
EndSub
SubMain()
division(25,0)
Console.ReadKey()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ...
Result: 0
Q 12. How to create User defined exceptions in VB.Net?
Ans.Creating User-Defined Exceptions-You can also define your own exception. User-
defined exception classes are derived from the ApplicationException class. The following
example demonstrates this −
Module exceptionProg
PublicClassTempIsZeroException:InheritsApplicationException
PublicSubNew(ByVal message AsString)
MyBase.New(message)
EndSub
EndClass
PublicClassTemperature
Dim temperature AsInteger=0
Sub showTemp()
If(temperature =0)Then
Throw(NewTempIsZeroException("Zero Temperature found"))
Else
Console.WriteLine("Temperature: {0}", temperature)
EndIf
EndSub
EndClass
SubMain()
Dim temp AsTemperature=NewTemperature()
Try
temp.showTemp()
Catch e AsTempIsZeroException
Console.WriteLine("TempIsZeroException: {0}", e.Message)
EndTry
Console.ReadKey()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
TempIsZeroException: Zero Temperature found
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the System.Exception
class.
You can use a throw statement in the catch block to throw the present object as −
Throw [ expression ]
The following program demonstrates this −
Module exceptionProg
SubMain()
Try
ThrowNewApplicationException("A custom exception _ is being thrown here...")
Catch e AsException
Console.WriteLine(e.Message)
Finally
Console.WriteLine("Now inside the Finally Block")
EndTry
Console.ReadKey()
EndSub
EndModule
When the above code is compiled and executed, it produces the following result −
A custom exception is being thrown here...
Now inside the Finally Block
Unit IV
GUI Programming
Ans. Two types of program paradigm are used in Programming. These procedures are
Oriented and Object oriented programming. All new-time programming languages use
Object oriented programming. OOPs are a software development paradigm used to solve
problems encountered in a process oriented approach. Object oriented programming does
not allow data to flow into the system during program development. This prevents it from
sudden change by any other function. In this, the problem is solved by object, and in this
data and function work with object. Only the object's function can access the object's data.
Thus, it can be said that object oriented programming is a programming approach in which
data and functions are tied together called classes and used by objects. Where its data and
functions are different store and process for each object. Here, memory space is allocated
for the object in which its data and functions store.
Features of Object Oriented Programming
Object Inheritance
Class Polymorphism
Object: It is the basic run-time entity of OOPs. Which represents an object (person,
place, a bank account etc.). object is the variable of the class that executes the class
and processes the data using the methods available in it. Once the object is created,
it takes up space like other variables in memory.
Class: Class is a user defined data type that contains data and code that is used by
the object. A class is a structure that defines the object's working. Many objects can
be created after creating a class. Thus it can be said that class is a collection of
objects of the same type.
Data Abstraction and Encapsulation: Binding data and functions together is called
Encapsulation. This is the most important feature of the class. In this, the data cannot
be accessed outside the class, only the functions of the class can access it. The data
abstraction is from inputting and outputing the data without background process
details in which it is performed by the functions of the class.
Inheritance: This is an important feature of OOPs that provides the facility of one
class to access the features of another class. In this, the object of one class can
access and use the properties of the other class as well. It implements the feature of
reuseability where to add new features to a class by creating a new class and
implementing the features of the old class in it as well as adding codes to the new
class.
Ans. Inheritance-Inheritance is an important feature of VB.Net that allows one class to use
another class feature. It allows to create a new class based on the already created class.
This supports reusability where they do not have to be recreated to add a feature or use the
features of the old class, inheritance from the old class and add them to the new class. The
class to be inherited is called base-class or parent class and the inherited class is derived or
child class.
Inheriting a class
To inherit the base class in the derived class, use the Inherits keyword and define the name
of the base class. After inheriting all the properties, methods, events, fields and constants of
the base class can be used in the derived class.
Inheritance Modifiers
Visual basic .Net provides some class level modifiers for inheritance.
MustInherit: On using it, it becomes mandatory to use the class in the base class. It
can only be used as a base class.
Inheritance to access type of both Base and Derived class must be equal only if
inheritance is possible.
Ans. All members of a class can directly access any other member. But we have to use
different types of Access Modifiers Provided by VB.NET to decide which Members of
another Class can access and how they can access. Members are declared in the following
way in a class created using object oriented programming in VB.NET -
Public
When a class is defined with a public Access Modifier, the members with publicAccess of
that class are equally Directly Accessible in the same Assembly and External Assembly.
Therefore, this type of class can be inherited in any assembly without any restriction.
Private
When a class is defined with a private Access Modifier, members with privateAccess of that
class are neither directly accessible in the Derived Class of the same Assembly nor in the
Derived Class of External Assembly. That is, such members are not directly accessible in
any derived class, but are always accessible through some public method.
Friend
This gives Friendly access to the variable, which means that if a Variable is Declared Friend
then that Variable can be used in the same class or used in the same Assembly.
Protected
When a class is defined with a protected Access Modifier, the members with protected
access to that class are Directly Accessible in the same Assembly and Derived Classes in
the External Assembly, but for Members outside the Derived Class, these Members are
Private Members' Behave in a manner.
Same Name: The names of all overloaded procedures must be the same.
Different Signature: All overloaded procedures should have at least one of the
following differences only if the procedures can be overloaded.
1. Number of Parameters
2. Order of Parameters
3. Data Types of Parameters
4. Number of Type Parameters
5. Return Type
Example:
End Function
Dim s As Integer
s = (a + b + c) / 2
End Function
End Class
Ans. In mybase keyword inheritance, the base class's overrided method is used to call.
When ever the overrided method of base class is required while inheritance, then you can
call using the mybase keyword.
Example: When calculating the area of the circle as well as when calculating the area of the
Cone, then the area of the circle class needs to be override. In this, mybase is used to call
the area method of base class (Circle).
Circle.vb
Get
radius = cradius
End Get
msgbox(“Wrong Input:”)
Else
cradius = value
End If
End Set
End Property
End Function
End Class
Cone.vb
Inherits Circle
Dim l As Double
Get
length = l
End Get
l = value
End Set
End Property
End Class
Mybase is not a real object, so assign value to variable by it, pass in procedure etc.
can not do.
Ans. MyClass Keyword- This keyword, like mybase, is used to call the overrided method of
the derived class when overriding a method. This makes sure that the called method is the
overrided method of this derived class.
End function
MyClass is not a real object, so assign value to variable by it, pass in procedure etc.
can not do.
Myclass cannot be used with methods that cannot be override the base class.
An application or any pre-made file can be used for OLE Object. For this this Dialogbox
contains Create New and Create From File Options. To link to a new application, select the
Create New option and select the object. And clicking OK button creates an Icon or Select
Object on the form. The features of that application can be accessed in your program by
double clicking on it.
Example: Selecting Excel Sheet
Example:
ADO.NET Components
The two main components of ADO.NET for accessing and manipulating data are the .NET
Framework data providers and the DataSet.
The .NET Framework Data Providers are components that have been explicitly designed for
data manipulation and fast, forward-only, read-only access to data. The Connection object
provides connectivity to a data source. The Command object enables access to database
commands to return data, modify data, run stored procedures, and send or retrieve
parameter information. The DataReader provides a high-performance stream of data from
the data source. Finally, the DataAdapter provides the bridge between the DataSet object
and the data source. The DataAdapter uses Command objects to execute SQL commands
at the data source to both load the DataSet with data and reconcile changes that were
made to the data in the DataSet back to the data source.
The DataSet
When you decide whether your application should use aDataReader or aDataSet, consider
the type of functionality that your application requires. Use aDataSetto do the following:
Cache data locally in your application so that you can manipulate it. If you only need
to read the results of a query, the DataReaderis the better choice.
If you do not require the functionality provided by the DataSet, you can improve the
performance of your application by using the DataReader to return your data in a forward-
only, read-only manner. Although the DataAdapter uses the DataReader to fill the
contents of a DataSet, by using the DataReader, you can boost performance because you
will save memory that would be consumed by the DataSet, and avoid the processing that is
required to create and fill the contents of the DataSet.
LINQ to DataSet
LINQ to DataSet provides query capabilities and compile-time type checking over data
cached in a DataSet object. It allows you to write queries in one of the .NET Framework
development language, such as C# or Visual Basic.
LINQ to SQL
LINQ to SQL supports queries against an object model that is mapped to the data structures
of a relational database without using an intermediate conceptual model. Each table is
represented by a separate class, tightly coupling the object model to the relational database
schema. LINQ to SQL translates language-integrated queries in the object model into
Transact-SQL and sends them to the database for execution. When the database returns
the results, LINQ to SQL translates the results back into objects.
The ADO.NET Entity Framework is designed to enable developers to create data access
applications by programming against a conceptual application model instead of
programming directly against a relational storage schema. The goal is to decrease the
amount of code and maintenance required for data-oriented applications.
WCF Data Services is used to deploy data services on the Web or an intranet. The data is
structured as entities and relationships according to the specifications of the Entity Data
Model. Data deployed on this model is addressable by standard HTTP protocol.
Ans. ADO.Net object model is nothing but the structured process flow through various
components. The object model can be pictorially described as −
The data residing in a data store or database is retrieved through the data provider. Various
components of the data provider retrieve data for the application and update data.
An application accesses data either through a dataset or a data reader.
Datasets store data in a disconnected cache and the application retrieves data from
it.
Data Provider
A data provider is used for connecting to a database, executing commands and retrieving
data, storing it in a dataset, reading the retrieved data and updating the database.
The data provider in ADO.Net consists of the following four objects −
1 Connection
This component is used to set up a connection with a data source.
2
Command
A command is a SQL statement or a stored procedure used to retrieve, insert, delete or modify data
in a data source.
3
DataReader
Data reader is used to retrieve data from a data source in a read-only and forward-only mode.
4
DataAdapter
This is integral to the working of ADO.Net since data is transferred to and from a database through a
data adapter. It retrieves data from a database into a dataset and updates the database. When
changes are made to the dataset, the changes in the database are actually done by the data
adapter.
The .Net Framework data provider for SQL Server - provides access to Microsoft
SQL Server.
The .Net Framework data provider for OLE DB - provides access to data sources
exposed by using OLE DB.
The .Net Framework data provider for ODBC - provides access to data sources
exposed by ODBC.
The .Net Framework data provider for Oracle - provides access to Oracle data
source.
The EntityClient provider - enables accessing data through Entity Data Model (EDM)
applications.
DataSet
Connecting to a Database
Example 1
We have a table stored in Microsoft SQL Server, named Customers, in a database named
testDB. Please consult 'SQL Server' tutorial for creating databases and database tables in
SQL Server.
Let us connect to this database. Take the following steps −
Choose the database object, Customers table in our example, and click the Finish
button.
Select the Preview Data link to see the data in
the Results grid −
Example 2
In this example, let us access data in a DataGridView control using code. Take the following
steps −
Double click the button control to add the required code for the Click event of the
button, as shown below −
ImportsSystem.Data.SqlClient
PublicClassForm1
PrivateSubForm1_Load(sender AsObject, e AsEventArgs) _
HandlesMyBase.Load
'TODO: This line of code loads data into the
'TestDBDataSet.CUSTOMERS' table.
You can move, or remove it, as needed.
Me.CUSTOMERSTableAdapter.Fill(Me.TestDBDataSet.CUSTOMERS)
'Set the caption bar text of the form.
Me.Text="tutorialspoint.com"
EndSub
PrivateSubButton1_Click(sender AsObject, e
AsEventArgs)HandlesButton1.Click
Dim connection AsSqlConnection=New sqlconnection()
connection.ConnectionString="Data Source=KABIR-DESKTOP; _
Initial Catalog=testDB;Integrated Security=True"
connection.Open()
Dim adp AsSqlDataAdapter=NewSqlDataAdapter _
("select * from Customers", connection)
Dim ds AsDataSet=NewDataSet()
adp.Fill(ds)
DataGridView1.DataSource= ds.Tables(0)
EndSub
EndClass
Example 3
PublicClassForm1
PrivateSubForm1_Load(sender AsObject, e
AsEventArgs)HandlesMyBase.Load
' Set the caption bar text of the form.
Me.Text = "tutorialspont.com"
End Sub
Private Function CreateDataSet() As DataSet
'creating a DataSetobjectfor tables
Dim dataset AsDataSet=NewDataSet()
' creating the student table
Dim Students As DataTable = CreateStudentTable()
dataset.Tables.Add(Students)
Return dataset
End Function
Private Function CreateStudentTable() As DataTable
Dim Students As DataTable
Students = New DataTable("Student")
' adding columns
AddNewColumn(Students,"System.Int32","StudentID")
AddNewColumn(Students,"System.String","StudentName")
AddNewColumn(Students,"System.String","StudentCity")
' adding rows
AddNewRow(Students, 1, "Zara Ali", "Kolkata")
AddNewRow(Students, 2, "Shreya Sharma", "Delhi")
AddNewRow(Students, 3, "Rini Mukherjee", "Hyderabad")
AddNewRow(Students, 4, "Sunil Dubey", "Bikaner")
AddNewRow(Students, 5, "Rajat Mishra", "Patna")
Return Students
End Function
Private Sub AddNewColumn(ByRef table As DataTable, _
ByVal columnType As String, ByVal columnName As String)
Dim column As DataColumn = _
table.Columns.Add(columnName, Type.GetType(columnType))
End Sub
When the above code is executed and run using Start button available at the
Microsoft Visual Studio tool bar, it will show the following window −
Clicking the Fill button displays the table on the data grid view control −
Ans. In VB.NET, we can get data from Database through Data Bound Controls and display
the data in these controls on the form. Here the following steps are followed to display the
data through Text Box (Data Bound Controls) -
Step 1: Create a new project in VB.NET and design a new form. Connected to the database
with the help of oledb Data Adapter and create Dataset.
Step 2: From the Tool Box, design three Text Boxes and one button on the form.
Step 3: By selecting the Text Box, in the Properties window of the text box, we set the Data
Bindings and Dataset properties. The same steps are done for the remaining Text Boxes.
Step 4: Under the Form do the following Coding –
Ans. Data Receiving in Data Grid: Here we are creating an example where the data can be
accessed to help the programmer. For this, follow the following steps -
• Start a new Windows application project and name it "Exam".
• Drag the OleDb Data Adapter Control from the toolbox and drop it onto the form, then the
wizard of the data adapter starts.
• After the wizard is finished, the controls are inserted into the tray.
• Dataset is required to get the data.
• Once DataSat is created, the Data Grid control from the toolbox is created on the form from
the toolbox.
• Selects the data source property of this control, then the list comes under it.
• Selects Data Set 11. Groups option from this list.
In order to get the data from the adapter, in the load event of the form, coding as follows-
Private Sub Form1 Load (By Val Sender As System. Object, By Val e As System. Event
Args)
Handles My Base. Load
End Sub