GAD (22034)
Unit-1
Overview of GUI Programming
1.1 Introduction to .Net Frame Work
Visual Basic .NET (VB.NET) is an object-oriented computer programming language
implemented on the .NET Framework. Although it is an evolution of classic Visual Basic
language, it is not backwards-compatible with VB6, and any code written in the old version
does not compile under VB.NET.
Like all other .NET languages, VB.NET has complete support for object-oriented concepts.
Everything in VB.NET is an object, including all of the primitive types (Short, Integer, Long,
String, Boolean, etc.) and user-defined types, events, and even assemblies. All objects
inherits from the base class Object.
What is .Net Frame Work
The .Net framework applications are multi-platform applications. The framework has been
designed in such a way that it can be used from any of the following languages: Visual Basic,
C#, C++, Jscript, and COBOL, etc. it supports more than 60 languages.
The .Net framework is a revolutionary platform that helps you to write the following types of
applications −
Windows applications
Web applications
Web services
The main objective of this framework is to develop an application that can run on
the windows platform. The current version of the .Net framework is 4.8.
Fig 1.1 shows various component of .Net Frame There are following components of .NET
Framework:
1. CLR (Common Language Runtime)
2. CTS (Common Type System)
3. BCL (Base Class Library)
4. CLS (Common Language Specification)
5. FCL (Framework Class Library)
6. .NET Assemblies
7. XML Web Services
8. Window Services
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Fig. 1.1 .Net Frame work Component
CLR (common language runtime)
It is an important part of a .NET framework that works like a virtual component of the .NET
Framework to executes the different languages program like c#, Visual Basic, etc. A CLR
also helps to convert a source code into the byte code, and this byte code is known as CIL
(Common Intermediate Language) or MSIL (Microsoft Intermediate Language). After
converting into a byte code, a CLR uses a JIT compiler at run time that helps to convert a CIL
or MSIL code into the machine or native code.
CTS (Common Type System)
It specifies a standard that represent what type of data and value can be defined and managed
in computer memory at runtime. A CTS ensures that programming data defined in various
languages should beinteract with each other to share information. For example, in C# we
define data type as int, while in VB.NET we define integer as a data type.
BCL (Base Class Library)
The base class library has a rich collection of libraries features and functions that help to
implement many programming languages in the .NET Framework, such as C #, F #, Visual C
++, and more. Furthermore, BCL divides into two parts:
1. User defined class library
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
o Assemblies - It is the collection of small parts of deployment an application's
part. It contains either the DLL (Dynamic Link Library) or exe (Executable)
file.
1. In LL, it uses code reusability, whereas in exe it contains only output
file/ or application.
2. DLL file can't be open, whereas exe file can be open.
3. DLL file can't be run individually, whereas in exe, it can run
individually.
4. In DLL file, there is no main method, whereas exe file has main
method.
2. Predefined class library
o Namespace - It is the collection of predefined class and method that present in
.Net. In other languages such as, C we used header files, in java we used
package similarly we used "using system" in .NET, where using is a keyword
and system is a namespace.
CLS (Common language Specification)
It is a subset of common type system (CTS) that defines a set of rules and regulations
which should be followed by every language that comes under the .net framework. In
other words, a CLS language should be cross-language integration or interoperability.
For example, in C# and VB.NET language, the C# language terminate each statement
with semicolon, whereas in VB.NET it is not end with semicolon, and when these
statements execute in .NET Framework, it provides a common platform to interact
and share information with each other.
Difference Between VB. NET and Visual Basic
VB .NET Visual Basic
It stands for Visual Basic. Network Enables It is a programming language developed by
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Technology. It is also developed by Microsoft for the fastest development of a
Microsoft, and this language was based on window-based operating system as well as
the .Net Framework. Furthermore, it is applications.
specially designed for VB developers.
It is a modern, fully object-oriented VB is the predecessor of VB.NET and was not
language that replaced VB6. an object-oriented language. So, it is not
actively maintained.
A VB.NET uses the Common Language Visual Basic uses the VB-Runtime
Runtime (CLR) component of .Net environment.
Framework at runtime. It has better features
and design implementation as compared to
VB-Runtime.
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.
In VB.NET, data is handled using the Data Connectivity and handling are done
ADO.net protocol. through DAO, RDO, and ADO (ActiveX Data
Object) protocol,
Object does not support default property. The Object support default property of virtual
basic.
In the VB.Net parameter are passed by a In VB, most of the parameters are passed by
default value. reference.
A Multithreaded application can be It does not support the multithread concept.
developed in VB.NET.
Exploring VB .Net IDE
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Unit-2
Decision Control and Loop Control
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
2.1 Data Types Available in VB.Net
VB.Net provides a wide range of data types. The following table shows all the data types
available −
Data Type Storage Allocation Value Range
Boolean Depends on implementing True or False
platform
Byte 1 byte 0 through 255 (unsigned)
Char 2 bytes 0 through 65535 (unsigned)
Date 8 bytes 0:00:00 (midnight) on January 1, 0001
through 11:59:59 PM on December 31, 9999
Decimal 16 bytes 0 through +/-
79,228,162,514,264,337,593,543,950,335 (+/-
7.9...E+28) with no decimal point; 0 through
+/-7.9228162514264337593543950335 with
28 places to the right of the decimal
Double 8 bytes -1.79769313486231570E+308 through -
4.94065645841246544E-324, for negative
values
4.94065645841246544E-324 through
1.79769313486231570E+308, for positive
values
Integer 4 bytes -2,147,483,648 through 2,147,483,647
(signed)
Long 8 bytes -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807(signed)
Object Any type can be stored in a variable of type
4 bytes on 32-bit platform
Object
8 bytes on 64-bit platform
2.2 Operator in VB .Net
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. VB.Net is rich in built-in operators and provides following types of
commonly used operators −
Arithmetic Operators
Comparison Operators
Logical/Bitwise Operators
Bit Shift Operators
Assignment Operators
Arithmetic Operators
Following table shows all the arithmetic operators supported by VB.Net
Operator Description Example
^ Raises one operand to the power of another B^A will give 49
+ Adds two operands A + B will give 9
- Subtracts second operand from the first A - B will give -5
* Multiplies both operands A * B will give
14
/ Divides one operand by another and returns a floating point B / A will give
result 3.5
\ Divides one operand by another and returns an integer result B \ A will give 3
Comparison Operators
Following table shows all the comparison operators supported by VB.Net
Operator Description Example
= Checks if the values of two operands are equal or not; (A = B) is not true.
if yes, then condition becomes true.
<> Checks if the values of two operands are equal or not; (A <> B) is true.
if values are not equal, then condition becomes true.
> Checks if the value of left operand is greater than the (A > B) is not true.
value of right operand; if yes, then condition becomes
true.
< Checks if the value of left operand is less than the (A < B) is true.
value of right operand; if yes, then condition becomes
true.
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
>= Checks if the value of left operand is greater than or (A >= B) is not
equal to the value of right operand; if yes, then true.
condition becomes true.
<= Checks if the value of left operand is less than or (A <= B) is true.
equal to the value of right operand; if yes, then
condition becomes true.
Logical/Bitwise Operators
Following table shows all the logical operators supported by VB.Net
Operator Description Example
And It is the logical as well as bitwise AND operator. (A And B) is False.
If both the operands are true, then condition
becomes true. This operator does not perform
short-circuiting, i.e., it evaluates both the
expressions.
Or It is the logical as well as bitwise OR operator. If (A Or B) is True.
any of the two operands is true, then condition
becomes true. This operator does not perform
short-circuiting, i.e., it evaluates both the
expressions.
Not It is the logical as well as bitwise NOT operator. Not(A And B) is True.
Use to reverses the logical state of its operand. If
a condition is true, then Logical NOT operator
will make false.
Xor It is the logical as well as bitwise Logical A Xor B is True.
Exclusive OR operator. It returns True if both
expressions are True or both expressions are
False; otherwise it returns False. This operator
does not perform short-circuiting, it always
evaluates both expressions and there is no short-
circuiting counterpart of this operator.
AndAlso It is the logical AND operator. It works only on (A AndAlso B) is
Boolean data. It performs short-circuiting. False.
OrElse It is the logical OR operator. It works only on (A OrElse B) is True.
Boolean data. It performs short-circuiting.
IsFalse It determines whether an expression is False.
IsTrue It determines whether an expression is True.
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Assignment Operators
There are following assignment operators supported by VB.Net −
Operator Description Example
= Simple assignment operator, Assigns values C = A + B will assign value of A + B
from right side operands to left side operand into C
+= Add AND assignment operator, It adds C += A is equivalent to C = C + A
right operand to the left operand and assigns
the result to left operand
-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A
subtracts right operand from the left
operand and assigns the result to left
operand
*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A
multiplies right operand with the left
operand and assigns the result to left
operand
/= Divide AND assignment operator, It divides C /= A is equivalent to C = C / A
left operand with the right operand and
assigns the result to left operand (floating
point division)
\= Divide AND assignment operator, It divides C \= A is equivalent to C = C \A
left operand with the right operand and
assigns the result to left operand (Integer
division)
^= Exponentiation and assignment operator. It C^=A is equivalent to C = C ^ A
raises the left operand to the power of the
right operand and assigns the result to left
operand.
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Concatenates a String expression to a String Str1 &= Str2 is same as
variable or property and assigns the result to
the variable or property. Str1 = Str1 & Str2
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
2.3 Control Structure in VB .Net
1. IF Statement
2. IF –Else Statement
3. Select Statement.
VB.Net provides the following types of decision making statements.
Statement Description
If ... Then statement An If...Then statement consists of a
boolean expression followed by one or
more statements.
If...Then...Else statement An If...Then statement can be followed
by an optional Else statement, which
executes when the boolean expression is
false.
nested If statements You can use one If or Else if statement
inside another If or Else if statement(s).
Select Case statement A Select Case statement allows a variable
to be tested for equality against a list of
values.
Syntax for if-then statement is −
If condition Then
[Statement(s)]
End If
Where, condition is a Boolean or relational condition and Statement(s) is a simple or
compound statement. Example of an If-Then statement is –
Example of an If-Then statement is −
If (a <= 20) Then
c= c+1
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
End If
Module decisions
Sub Main()
'local variable definition
Dim a As Integer = 10
' check the boolean condition using if statement
If (a < 20) Then
' if condition is true then print the following
Console.WriteLine("a is less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
a is less than 20
value of a is : 10
The syntax of an If...Then... Else statement in VB.Net is as follows −
If(boolean_expression)Then
'statement(s) will execute if the Boolean expression is true
Else
'statement(s) will execute if the Boolean expression is false
End If
The syntax of an if...else if...else statement in VB.Net is as follows −
If(boolean_expression 1)Then
' Executes when the boolean expression 1 is true
ElseIf( boolean_expression 2)Then
' Executes when the boolean expression 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the boolean expression 3 is true
Else
' executes when the none of the above condition is true
End If
The syntax for a Select Case statement in VB.Net is as follows −
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
[ elsestatements ] ]
End Select
Where,
expression − is an expression that must evaluate to any of the elementary data type in
VB.Net, i.e., Boolean, Byte, Char, Date, Double, Decimal, Integer, Long, Object,
SByte, Short, Single, String, UInteger, ULong, and UShort.
expressionlist − List of expression clauses representing match values for expression.
Multiple expression clauses are separated by commas.
statements − statements following Case that run if the select expression matches any
clause in expressionlist.
elsestatements − statements following Case Else that run if the select expression does
not match any clause in the expressionlist of any of the Case statements.
Example
Module decisions
Sub Main()
'local variable definition
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
2.4 Loop Statement in VB .Net
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages –
Loop Type Description
Do 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.
For...Next It repeats a group of statements a specified number of times
and a loop index counts the number of loop iterations as the
loop executes.
For Each...Next It repeats a group of statements for each element in a
collection. This loop is used for accessing and manipulating
all elements in an array or a VB.Net collection.
While... End While It executes a series of statements as long as a given condition
is True.
The syntax for this Do loop construct is –
Do
[ statements ]
[ Continue Do ]
[ statements ]
[ Exit Do ]
[ statements ]
Loop { While | Until } condition
Example
Do
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
The syntax for this loop construct is −
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
Example
Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
The syntax for this loop construct is −
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Example
Module loops
Sub Main()
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
'displaying the values
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
1
3
5
7
9
It executes a series of statements as long as a given condition is True.
The syntax for this loop construct is −
While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While
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
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
It is not exactly a looping construct. It executes a series of statements that repeatedly refers to
a single object or structure.
The syntax for this loop construct is −
With object
[ statements ]
End With
Example
Module loops
Public Class Book
Public Property Name As String
Public Property Author As String
Public Property Subject As String
End Class
Sub Main()
Dim aBook As New Book
With aBook
.Name = "VB.Net Programming"
.Author = "Zara Ali"
.Subject = "Information Technology"
End With
With aBook
Console.WriteLine(.Name)
Console.WriteLine(.Author)
Console.WriteLine(.Subject)
End With
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
VB.Net Programming
Zara Ali
Information Technology
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
2.5 Forms Controls in VB .Net and Its Properties.
VB.NET Form Controls
A Form is used in VB.NET to create a form-based or window-based application. Using the
form, we can build a attractive user interface. It is like a container for holding different
control that allows the user to interact with an application. The controls are an object in a
form such as buttons, Textboxes, Textarea, labels, etc. to perform some action. However, we
can add any control to the runtime by creating an instance of it.
A Form uses a System.Windows.Form namespace, and it has a wide family of controls that
add both forms and functions in a Window-based user interface.
Controls are as follows
1. Button
2. Text Box
3. Label
4. Radio button
5. Check box
6. List box
7. Combo Box
8. Picture Box
9. Panel
10. Tab Control
11. Timer
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Unit 3
Object Oriented Programming in VB .Net
3.1 Sub Procedure and Function
Sub Procedures:
A subprocedure is a group of VB.NET statements. It begins with a Sub keyword and ends
with End Sub keywords. A subprocedure is also called a subroutine. It is used to execute a
certain block of statements consists the body of the procedure. It is called explicitly by its
name whenever it is required to perform a certain task. It can be called any number of
times. The subprocedure returns control to the calling code after performing a task.
Sub <subname> [(parameter list)]
Vb statements
End Sub
Function Procedures:
A function procedure is a group of VB.NET statements. It begins with a Function keyword
and ends with an End Function keyword. It is generally used to perform a task and return a
value back to the calling code. It may have multiple return points to the calling code. A part
from return stamens, End Function, or Exit function also returns control to the calling
procedure.
Structure of Function Procedure:
Function <Functionname> [(parameter list)] As return type
Vb statements
End Function
Comparison between SubProcedure and Function:
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Parameters Sub Procedures Functions
A subprocedure is not associated with an A function is also not associated
1 event. with an event.
A subprocedure is called, whenever it is A function is called, whenever a
required to perform certain tasks. It value is required to be returned to
returns control to the calling code after the calling code after performing
2 performing a task. a task.
A subprocedure does not return a value to Functions return a value to the
3 the calling code. calling code.
A sub procedure cannot be used with an Functions are used in an
4 expression. expression.
Subprocedure helps to make the code In functions, it is not easy to
5 readable, and easy to modify and debug. modify and debug the code.
Sub procedure is a generalized type of A function is a specific type of
6 function. procedure
A subprocedure is declared with the A function is declared with the
7. keyword Sub. keyword Function.
3.2 Class object in VB .Net
Class Definition
A class definition starts with the keyword Class followed by the class name; and the class
body, ended by the End Class statement. Following is the general form of a class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _
Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Example
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
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
When the above code is compiled and executed, it produces the following result −
Volume of Box1 : 210
Volume of Box2 : 1560
3.3 Constructor and Destructors in VB .Net
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
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)
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
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
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
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.
Class Line
Private length As Double ' Length of a line
Public Sub New() 'parameterised constructor
Console.WriteLine("Object is being created")
End Sub
Protected Overrides Sub Finalize() ' destructor
Console.WriteLine("Object is being deleted")
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())
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Console.ReadKey()
End Sub
End Class
When the above code is compiled and executed, it produces the following result −
Object is being created
Length of line : 6
Object is being deleted
3.4 Inheritance –Simple Inheritance using override keyword
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
3.5 Overloading, Overriding and shadowing
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
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.
' 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
When the above code is compiled and executed, it produces the following result −
Total area: 35
3.6 Exception Handling.
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.
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Catch − A program catches an exception with an exception handler at the place in a
program where you want to handle the problem. The Catch keyword indicates the
catching of an exception.
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
Assuming a block will raise an exception, a method catches an exception using a combination
of the Try and Catch keywords. A Try/Catch block is placed around the code that might
generate an exception. Code within a Try/Catch block is referred to as protected code, and the
syntax for using Try/Catch looks like the following −
Try
[ tryStatements ]
[ Exit Try ]
[ Catch [ exception [ As type ] ] [ When expression ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]End Try
Exception Classes in .Net Framework
Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException Handles errors generated when a method
refers to an array index out of range.
System.ArrayTypeMismatchException Handles errors generated when type is
mismatched with the array type.
System.NullReferenceException Handles errors generated from deferencing
a null object.
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
System.DivideByZeroException Handles errors generated from dividing a
dividend with zero.
System.InvalidCastException Handles errors generated during
typecasting.
System.OutOfMemoryException Handles errors generated from insufficient
free memory.
System.StackOverflowException Handles errors generated from stack
overflow.
Example
Module exceptionProg
Sub division(ByVal num1 As Integer, ByVal num2 As Integer)
Dim result As Integer
Try
result = num1 \ num2
Catch e As DivideByZeroException
Console.WriteLine("Exception caught: {0}", e)
Finally
Console.WriteLine("Result: {0}", result)
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
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
Unit-4
Data Access in VB .Net
4.1 Architecture of ADO .Net
ActiveX Data Objects (ADO)
It is a module of .Net Framework which is used to establish connection between application
and data sources. Data sources can be such as SQL Server and XML. ADO.NET consists of
classes that can be used to connect, retrieve, insert and delete data.
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
All the ADO.NET classes are located into System.Data.dll and integrated with XML classes
located into System.Xml.dll.
ADO.NET has two main components that are used for accessing and manipulating data are
the .NET Framework data provider and the DataSet.
Fig. 4.1 Architecture of ADO .Net
.NET Framework Data Providers
These are the components that are designed for data manipulation and fast access to data. It
provides various objects such as Connection, Command, DataReader and
DataAdapter that are used to perform database operations.
The DataSet
It is used to access data independently from any data resource. DataSet contains a collection
of one or more DataTable objects of data. The following diagram shows the relationship
between .NET Framework data provider and DataSet.
4.2 Accessing Data with Server Explorer
4.3 Data Providers
NET Framework Data Providers Objects
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Following are the core object of Data Providers.
Object Description
Connection It is used to establish a connection to a specific data
source.
Command It is used to execute queries to perform database
operations.
DataReader It is used to read data from data source. The
DbDataReader is a base class for all DataReader objects.
DataAdapter It populates a DataSet and resolves updates with the data
source. The base class for all DataAdapter objects is the
DbDataAdapter class.
4.4 Connections and data Reader, Data Adapters and datasets
Part Description
It is used for establishing a connection between database and
Connection application. OleDBConnectionclass is used for a database like an oracle and
MS-Access. SqlConnection class is used for the MS-SQL database.
It is used to execute a command (Query) like (Select * from
Command Student). OleDBCommand class is used for a database like an oracle and
MS-Access. SqlCommand class is used for the MS-SQL database.
DataSet It contains a copy of the original database tables.
It is used to retrieve data from the database and update DataSet. In the case
of inserting, updating, or deleting data, it automatically updates the database
DataAdapter while DataSet is updated. OleDBDataAdapter class is used for a database
like an oracle and MS-Access. SqlDataAdapter class is used for the MS-
SQL database.
DataReader It is used to read or retrieve data from database to
application. OleDBDataReaderclass is used for a database like an oracle and
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
MS-Access. SqlDataReader class is used for the MS-SQL database.
4.5 Creating new data Connection
Establish Connection to Database
Connect to a database.
Select tab from top menu-bar TOOLS, then Connect to Database…
Browse your database file and click the OK button.
After connecting to the new database file create an object of OleDBConnection class
in case of a database like Oracle or MS-Access and create an object
of SqlConnection class in case of MS-SQL database.
4.6 Creating Dataset
Create a DataSet
Select tab from top menu-bar PROJECT, then click Add New Data Source…
Select the Database and click the Next button.
Select Dataset and click the Next button.
Choose the data connection and click the Next button.
Save the connection and click the Next button.
Select data tables from the connected database and click the Finish button.
Retrieve, Insert, Update, Delete Data
Create an object of OleDBDataAdapter class in case of a database like Oracle or MS-Access
and create an object of SqlDataAdapter class in case of an MS-SQL database. Pass
command and connection object via parameters.
By Using Command and DataReader
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
In this way we have to follow the below steps:
Steps:
1. Establish a database connection
2. Execute Command
3. Read Data
Establish Database Connection
Establish a database connection the same as we have done it in the above way of
communication.
Execute Command
After establishing database connection create an object of OleDBCommand in case of
databases like Oracle or MS-Access and SqlCommand in the case of MS-SQL database.
Pass command and connection object via parameters.
Invoke ExecuteNonQuery in the case while you don’t need to get values or
invoke ExecuteScalar in the case while you need to get only a single value or
invoke ExecuteReader in the case while you need to get all values.
4.7 data Grid controls and Displaying data in Data grid
DataGrid is used to display data in scrollable grid. It requires data source to populate data in
the grid. It is a server side control and can be dragged from the toolbox to the web form. Data
Source for the DataGrid can be either a DataTable or a database.
4.8 Data access using Data Adapter
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Unit-5
Data Binding and Deployment
5.1 Simple data binding using Text box ,Check box and Label
Simple data binding is the type of binding typical for controls such as a TextBox control or
Label control, which are controls that typically only display a single value. In fact, any
property on a control can be bound to a field in a database. There's extensive support for this
feature in Visual Studio.
The most common use of simple data binding involves binding a single data element, such as
the value of a column in a table, to a control on a form. You use this type of data binding for
controls that show only one value. Uses of simple data binding include binding data to text
boxes and labels.
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
Consider a scenario where a Windows Forms form needs to be created to display employee
details in the following way.
Steps
1. Press F4 to open the properties window.
2. Select the first TextBox to display its properties window.
3. Expand the (DataBindings) property.
4. Select the text property to enable the drop-down list. Click the drop-down list.
5. Add a project data source in the drop-down list.
1. Create a connection with the AdventureWorks database and select the
HumanResources.employee table.
2. Select the first TextBox. Expand "Other data source" ---> "Project data source" -->
"AdventureWorksdataset" --> "Employee" --> "EmloyeeId".
3. Select the second TextBox. Expand the DataBinding property then select "Text" --->
"Employee Binding source" then select column(National ID) from the list.
4. Similarly, bind TextBox3 and TextBox4 with the column contactid and Login ID.
5. Press F5. If everything goes well, you will see the following output:
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
5.2 Complex data Binding using ComboBox and Listbox
Complex data binding allows you to bind more than one data element to control. Using the
column example, complex data binding involves binding more than one column or row from
the underlying record source. Controls that support complex data binding include data grid
controls, combo boxes, and list boxes.
5.3 Deploying VB .Net Application
To deploy an application so that the end user can install it on the target computer, you begin
by opening an existing Visual Basic solution and project. No matter the type of project being
deployed, you perform a similar set of steps, as described in the following list:
1. Open an existing solution containing one or more projects.
2. Create a Setup project within the solution.
3. Configure the Setup project by specifying the type of project being deployed along with
any support files that need to be deployed with the project.
In addition, it is possible to define where the executable files will be placed on the target
computer, and any items to be created on the target computer’s Start menu
4. Build the Setup project to create the installer (Setup.exe and related files). Note that you
build a Setup project in the same way that you build a Windows Application project.
5. Test the Setup project on the local computer.
6. Distribute the Setup.exe program and any necessary files to the end user via removable
media, the Internet, or a company intranet.
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)
GAD (22034)
CREATING A SETUP PROJECT WITH A WIZARD
Created By, Prof .Sarika Kadlag (Mb no. 7588004970)