VBDotNet Notes-Unit 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

UNIT -I

.NET Framework
.NET Framework is one of the most widely used software development
environment. It is developed by Microsoft and it runs on Microsoft windows
operating system.
With .NET, Microsoft provides programmer, a single platform for developing
applications using different programming languages such as Visual Basic,
Visual C++, F#, C# and so on in an easy, secure and reliable way

Architecture of .NET Framework / Components of .NET Framework

Common Language Runtime


CLR (Common Language Runtime) is the heart of .Net Framework. CLR is an
Execution Environment for .Net Applications. It works as a layer between
Operating System and the applications written in .Net languages that conforms
to the Common Language Specification (CLS).
It provides an environment to run all the .Net Programs. The code which runs
under the CLR is called as Managed Code whereas the code that cannot be
directly executed by the CLR is known as Unmamaged Code

Language Compilers (e.g. C#, VB.Net, J#) will convert the Code to Microsoft
Intermediate Language (MSIL) which in turn will be converted to Native Code
by JIT compiler of CLR. Thus CLR facilitates the interoperability between
different .Net Languages

CLR defines the Common Type System (CTS), which is a standard type system
used by all .Net languages. All .NET programming languages uses the same
representation for common Data Types, so CLR is a language-independent
runtime environment . The Common Language Runtime environment is also
referred to as a managed environment, because during the execution of a
program it also controls the interaction with the Operating System.
Functions of CLR
 Converts MSIL code to Native Code
 Exception handling
 Type safety
 Memory management (using the Garbage Collector)
 Security
 Thread execution support
 Debugging
 Improved performance
 Language independency
 Platform independency
 Architecture independency
Windows Forms
Windows Form allows you to develop Windows based desktop applications that
users can install and run on their computers. The basic entity of a Windows
Form application is a form, which is a rectangular area on which you can place
various controls to design the UI of the application
ASP.NET and ASP.NET AJAX
ASP.NET is a Web development model which is used to develop interactive,
data-driven Web applications over the Internet
ASP.NET AJAX includes both client-side and server-side components that
allows developers to create web applications such that the applications do not
require complete reload of the page while making any modifications to the page

ADO.NET
ActiveX Data Objects.NET is the database technology of .net framework that is
used for working with data and databases of all types

.Net Remoting
NET Remoting is used to build distributed applications easily, whether
application components are all on one computer or spread out across the entire
world.

.NET Framework Class Library (FCL)


It is a huge library made up of a hierarchy of namespaces. It is the foundation
on which .NET Framework applications, components, and controls are built.
Each namespace contains classes, structures, interfaces, enumerations and
delegates. The System namespace is the root namespace for some of the
commonly used types in .NET framework

Common Type System


In .NET, every Data Type is internally represented by a class or structure. All
the classes and structures related to Data Types are collectively known as CTS.

Every language provides its own keywords for Data Types but internally all the
languages which run under .NET framework use the classes and structures
available in CTS.
For example, C# has int Data Type and VB.Net has Integer Data Type. Hence a
variable declared as int in C# or Integer in vb.net, finally after compilation, use
the same structure Int32 from CTS.

Common Language Specification


Common Language Specification is a subset of CTS. It defines a set of rules
and restrictions that every language must follow which runs under .NET
framework. The languages which follow these set of rules are said to be CLS
Compliant. In simple words, CLS enables cross-language integration. Thus Two
CTS Compliant languages do not require type conversion, when calling the
code written in one language supported by the .NET Framework

Features of .NET Framework / Benefits of .NET Framework


 OOPs Support: .NET provides a fully object-oriented environment. The
philosophy of .NET is – “Object is mother of all.” Languages like Visual
Basic.NET now support many of the OO features that were lacking
traditionally. Even primitive types like integer and characters can be
treated as objects – something not available even in OO languages like
C++.
 Support for Multiple Languages and Language Interoperability: The
CLR executes binary code called MSIL (Microsoft intermediate language),
and that code looks the same regardless of the original source language.
Within the .NET Framework is a compiler called the Just-In-Time, or JIT,
compiler. It compiles the MSIL down to machine specific code. All .NET –
enabled languages use the same data types and the same interfacing
conventions. This makes possible for all .NET language to interoperate
transparently.
 Cross-platform support – Any windows operating system that supports
the Common Language Runtime (CLR) can execute a .NET application,
i.e. .NET application enables interoperability between multiple windows
system
 Rich Functionality out of the box: .NET framework contains hundreds
of classes that provide variety of functionality ready to use in the
application to perform many operations such as file IO, network
communication and so on.
 Easy Deployment: Executable modules in .NET are self-describing.
Once the Common Language Runtime (CLR) knows where a module
resides, it can find out everything else it needs to know to run the
module, such as the module’s object interface and security requirements,
from the module itself. That means a module can just be copied to a new
environment and immediately executed.
 Code Access Security: .NET supplies a standard security mechanism,
available to all parts of the application and also gives the automatic
access to benefits such as garbage collection (which destroys objects and
reclaims memory for you) and more.
 Debugging Tools: .NET provides integrated debugging tools. Any
language that targets the .NET Framework can be debugged with that
single debugger.
 Distributed Systems: Microsoft.NET supports developing globally
distributed systems using which from servers to Wireless Palmtops, with
everything in between, will share the same general platform, with
versions of .NET available for all of them, and with each of them able to
integrate transparently with the others.
 Richer User Interface: There are commonly used controls, such as
Labels and Text Boxes, in both, with similar sets of properties and
method and hence development of the internet environment looks very
much like development for other types of software. The built-in
intelligence of Web Forms allows rich, browser-independent screens to be
developed quickly, and to be easily integrated with compiled code.
Microsoft has announced an initiative for the future called the Universal
Canvas which builds upon the XML standards to transform the internet
from a Read only environment into a read/write platform, enabling users
to interactively create, browse, edit and analyze information. The
universal canvas can bring together multiple sources of information
anywhere in the world to enable seamless data access and use.
 Extendibility: The completely object-based approach of .NET is designed
to allow base functionality to be extended through inheritance (unlike
COM) and the platform’s functionality is appropriately partitioned to
allow various parts (such as the just-in-time compilers) to be replaced as
new versions are needed. It is likely that, in the future, new ways of
interfacing to the outside world will be added to the current trio of
windows Form, Web Forms, and Web Services such as universal Canvas.
 Portability of compiled Applications: .NET allows the future possibility
of moving software to other hardware and operating system platforms.
The ultimate goal is that compiled code produced on one implementation
of .NET (such as Windows) could be moved to another implementation of
.NET on a different operating system merely by copying the compiled
code over and running it.
 Integrity with COM: .NET integrates very well with COM-based software.
The .NET Framework wraps COM components and exposes an interface
that .NET components can work with. This is absolutely essential to the
quick acceptance of .NET, because it makes .NET interoperable with a
tremendous amount of older COM-based software. .NET provides a
possible solution to DLL Hell, and removes much of the complexity of
dealing with COM and the registry. .NET allows you to run components
locally without requiring the calling application to go to the registry to
find components.

Microsoft Intermediate Language (MSIL)


Microsoft Intermediate Language (MSIL) is a CPU-independent set of
instructions that can be efficiently converted to the native code by JIT compiler
of CLR.
Assembly
Assembly is a primary unit of deployment in a NET Framework application.
Assembly is really a collection of types and resource information that are built
to work together and form a logical unit of functionality.

INTRODUCTION TO VB.NET
Visual Basic .NET (VB.NET) is an object-oriented computer programming
language implemented on the .NET Framework.
Some of the features of VB.Net are
 Boolean Conditions
 Automatic Garbage Collection
 Standard Library
 Assembly Versioning
 Properties and Events
 Delegates and Events Management
 Easy-to-use Generics
 Indexers
 Conditional Compilation
 Simple Multithreading
Simple VB.Net Program
A VB.Net program basically consists of the following parts:
 Namespace declaration
 A class or module
 One or more procedures
 Variables
 The Main procedure
 Statements & Expressions
 Comments
The following program displays the message “Hello World” in the Console
Window
Imports System
Module Module1
'This program will display Hello World
Sub Main()
Console.WriteLine("Hello World")
Console.ReadKey()
End Sub
End Module
Variables
Variable is a temporary storage location for data in your application. It can
hold the result of a specific calculation, information received from user at
runtime or piece of data that you want to display on a page

Variable naming conventions


 Variable name can contain digits, alphabets and the underscore
character
 First character should not be a digit
 Keywords should not be used as variable name. However it can be used if
it is prefixed with the @ character
 Variable names are not case sensitive (i.e) variable names sum and Sum
are treated as same in Vb.NET

Variables can be declared in two ways


 Explicit Variable declaration
 Implicit Variable declaration
Explicit Variable declaration
Here we declare the variable explicitly by specifying variable name and type
after the Dim statement. It is strongly recommended method for variable
declaration.
Syntax
Dim VariableName as Type [ = Initial value]
Examples
Dim m, n as Single
Dim Fact as Integer = 1
Dim s as String
Dim p as Point = new Point(12,15)
Implicit Variable declaration
We can declare the variable implicitly that is simply by using the variable
without declaring it first.
Implicit variable declaration is not allowed by default. We have to place Option
Explicit Off at the top of the page to allow implicit variable declaration.
Example
Option Explicit Off
Public class Form1
Private sub form1_load(…)
s= “Hello”
MsgBox(s)
End sub
End Class
Another method is to use Option Infer Statement. If Option Infer is set to ON,
VB.NET will deduce or infer the type of variable by examining the assignment
you make.
Example
Dim a = 10
It is equivalent to Dim a as Integer=10
Implicit variable declaration is a risky method as it results in misspelled
variable name and other errors.

Constants
Constant is a meaningful name that takes place of a number or text string that
does not change throughout the execution of a program.
Constants are declared with “const” keyword as follow
const PI as Double = 3.1415
Benefits of constants
 Increases the readability of code
 Makes global changes easier to accomplish
 Reduce programming mistakes
Boxing and UnBoxing
Boxing and unboxing are important concepts in VB.NET's type system. With
Boxing and Unboxing, one can link between value-types and reference-types by
allowing any value-type to be converted to and from object type.

Boxing is a mechanism in which value type is converted into reference type. It


is implicit.
Unboxing is a mechanism in which reference type is converted into value type.
It is explicit conversion process.

Program to show Boxing and Unboxing


Module Module1
Sub Main()
Dim i As Integer = 10
Dim j As Integer
Dim o As Object
' boxing
o=i
'unboxing
j = CInt(o)
Console.WriteLine("Value of o object : " & o)
Console.WriteLine("Value of j : " & j)
Console.ReadLine()
End Sub
End Module
This example shows both boxing and unboxing. When a variable of a value type
needs to be converted to a reference type, an object box is allocated to hold the
value, and the value is copied into the box.

Unboxing is just the opposite. When an object box is cast back to its original
value type, the value is copied out of the box and into the appropriate storage
location

Data Types
Data types specify the size and type of values that can be stored. In Visual
Basic, data types are classified according to whether a variable of a particular
type stores its own data or a pointer to the data. If it stores its own data it is
a value type; if it holds a pointer to data elsewhere in memory it is a reference
type.
`

Value Types
A data type is a value type if it holds the data within its own memory
allocation. Value types are of fixed length and stored on the stack. Value types
include the following:
 All primitive data types
 Integer Types –sbyte, byte, short ,ushort, int, uint, long, ulong
 Floating point types – float, double, decimal
 Char type
 Boolean type
 Structures
 Enumerations
Integer Types
The Integer type is used to represent a whole number. Integer data types
include the following types.

Data Type .Net Type Name Size

Byte(unsigned) System.Byte 8 bits


Short(signed) System.Int16 16 bits
Integer(signed) System.Int32 32 bits
Long(signed) System.Int64 64 bits
SByte(signed) System.Sbyte 8 bits
UShort(unsigned) System.Uint16 16 bits
UInteger(unsigned) System.Uint32 32 bits
ULong(unsigned) System.Uint64 64 bits

Floating point types


It is used to represent fractional values. Floating point data types includes the
following types
Data Type .Net Type Name Size

Single System.Single 32 bits


Double System.Double 64 bits
Decimal System.Decimal 128 bits

Single Type
It is used to represent fractional number with seven decimal digits of precision.
Append F to treat numeric literal as Single
Double Type
It is used to represent fractional number with 15 decimal digits of precision.
Append R to treat numeric literal as Double
Decimal Type
It is more precise than single or double. It has 28 decimal digits of precision.
Append D to treat numeric literal as Decimal
Char Type
It is used to represent a single Unicode character. It is of 2 bytes in length.
Append c when initializing a char
Boolean Type
Boolean type represents the Boolean value true or false. It is assigned 16 bits.
Structure Type
The structure data type is used to define a composite date type.
Defining a Structure
Public Structure Point
Dim x as Integer
Dim x as Integer
End Structure
Accessing a Structure
Dim p as Point
p.x=100
p.y=200
Enum Type
The Enum type is used to represent a set of named constants
Example
Enum Direction
West
East
North
South
End Enum
Reference Type
A reference type contains a pointer to another memory location that holds the
data. Reference types are of variable length and stored on the heap. Reference
types include the following:
 Object
 String
 Class
 Interface
 Delegate
 Arrays
Object Type
The Object type is a predefined referenced type. It serves as the base class for
all predefined and user defined classes.
String Type
The String type is also a predefined reference type. It is used for creating and
manipulating strings. We can perform various operations on string, such as
copying, comparing, searching, concatenating and so on.
Classes
Classes provide the best approach to group together the logically related items
and functions that work on them
Interface
Interfaces are a collection of members, such as methods, delegates, events and
Properties which are to be implemented by classes
Delegates
Delegates are used to encapsulate a method with a specific signature. It is
similar to function pointer in C++.
Arrays
Arrays are used to store a fixed size sequential collection of elements of same
type.
Value type Reference type

Reference type store reference to the


Value type store real data
data.
Value type are stored on stack of Reference type are stored on heap of
memory memory
When passed as value type, new When passed as Reference type then
copy is created and passed. So, reference of that variable is passed. So,
changes to variable does not get changes to variable does get reflected
reflected back back
Value types are faster in access Reference types are slower in access.
Value type consists of primitive
Reference type consists of class, array,
data types, structures,
interface, delegates
enumerations.
Value types derive Reference types derive
from System.ValueType from System.Object
Value types cannot contain the Reference types can contain the value
value null. null.

Operators
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
 Concatenation Operators
Arithmetic Operators
Arithmetic operators are used in mathematical expressions. The following table
lists the arithmetic operators:

Assume integer variable A holds 5 and variable B holds 2, then:

Operator Description Example


+ Addition A + B will give 7
- Subtraction A - B will give 3
* Multiplication A * B will give 10
/ Division A / B will give 2.5
\ Integer Division (Whole No Division) A \ B will give 2
Mod Remainder Division A mod B will give 1
^ Exponentiation (Raising to a power) A ^ B will 25
Comparison Operators
Following table shows all the comparison operators supported by VB.Net.
Assume variable A holds 10 and variable B holds 20, then

Operator Description Example


= Equal to A = B will give false
<> Not Equal to A <> B will give true
< Less than A < B will give true
> Greater Than A > B will give false
<= Less than equal to A <= B will give true
>= Greater than equal to A >= B will give false

Logical/Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Following
table shows all the logical operators supported by VB.Net.

Assume variable A holds Boolean value True and variable B holds Boolean
value False, then

Operator Description Example


Logical as well as bitwise negation
NOT NOT A will give false
operator
Logical as well as bitwise A AND B will give
AND
Conjunction operator False
Logical as well as bitwise
OR A OR B will give true
disjunction operator
Logical as well as bitwise exclusion A XOR B will give
XOR
operator true
Short Circuiting Logical A AndAlso B will give
AndAlso
Conjunction operator False
Short Circuiting Logical Disjunction A OrElse B will give
OrElse
operator true

Truth Table for logical operator


A B Not A A and B A Or B A Xor B

False False True False False False

False True True False True True

True False False False True True

True True False True True False


AndAlso
When the left hand side is false, the condition of right hand side is never
evaluated
A B A AndAlso B

False Never Evaluated False

True False False

True True True

OrElse
When the left hand side is true, the condition of right hand side is never
evaluated
A B A AndAlso B

True Never Evaluated True

False True True

False False False

Bit Shift Operator


There are two bit shift operators. They are,
<< - Bit Shift Left Operator
>> - Bit Shift Left Operator

Concatenation Operator
Concatenation Operators are used to join multiple strings into a single string.
There are two concatenation operators namely “+” and “&”

Assignment Operator
= operator is user for assignment. It also serves as comparison operator.
The following are the shortcut assignment operators provided by VB.Net

Operation Long form syntax Shortcut Syntax

Addition x=x+6 x += 6

Subtraction x=x-6 x -= 6

Multiplication x=x*6 x *= 6
Division x=x/6 x /= 6

Integer Division x=x\6 x \= 6

Exponentiation x=x^6 x ^= 6

String x = x & “abc” x &= “abc”


Concatenation
x=x + ”abc” x +=”abc”

Operator Precedence
Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Operators with the highest precedence
appear at the top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first

Operator Precedence
() Parenthesis Highest
^ Exponentiation
- Unary negation
*,/
/ Integer division
Mod
+, -
<< , >>
All comparison operators (=, <>, <, <=, >, >=)
Not
And, AndAlso
Or, OrElse
Xor Lowest

Controls in Windows Forms


Control Class
The control class is the ultimate base class for all Windows Forms controls.
This class implements base functionalities, such as handling user input
through keyboard and mouse and defining position and size of a control that
displays information to the user. It is defined in the namespace
System.Windows.Forms namespace.

The Control class defines properties, methods, and events, which are common
to all Windows Forms controls

Some Properties of Control class


 Font : Gets or sets the font of the text displayed by the control.
 BackColor : Gets or sets the background color for the control.
 ForeColor : Gets or sets the foreground color of the control
 Margin : Gets or sets the space between controls.
 Size : Gets or sets the height and width of the control.
 Dock : Gets or sets which control borders are docked to its parent
control and determines how a control is resized with its parent.
 Text : Gets or sets the text associated with this control.
 Visible : Gets or sets a value indicating whether the control and all its
child controls are displayed.
 Enabled : Gets or sets a value indicating whether the control can
respond to user interaction.
 Parent : Gets or sets the parent container of the control
Some methods of Control class
 Hide() : Conceals the control from the user
 Show() : Displays the control to the user.
 Focus() : Sets input focus to the control.
 Select() : Activates the control.
Some Events of Control class
 Click : Occurs when the control is clicked.
 DoubleClick : Occurs when the control is double-clicked.
 GotFocus : Occurs when the control receives focus.
 LostFocus : Occurs when the control loses focus.
 KeyDown : Occurs when a key is pressed down while the control has
focus.
 KeyPress : Occurs when a key is pressed while the control has focus.
 KeyUp : Occurs when a key is released while the control has focus.

Label Control
The Label control is one of the most commonly used windows Form controls.
Label controls are typically used to provide descriptive text for a control. For
example, you can use a Label to add descriptive text for a TextBox control to
inform the user about the type of data expected in the control.

Label is a non selectable control. Unlike other controls, it is not meant to


accept input from user. Instead it displays a text that user can view but not
select or modify.
Some Properties of Label
 BorderStyle : Gets or sets the border style for the control.
 Image : Gets or sets the image that is displayed on a Label.
 ImageAlign : Gets or sets the alignment of an image that is displayed in
the control.
 Text : Gets or sets the text associated with this control.
 TextAlign : Gets or sets the alignment of text in the label.
TextBox Control
TextBox control lets you enter text on a Windows form at runtime. Typically, it
is used to display or accept a single line of text. You can use the Multiline and
ScrollBars properties to enable multiple lines of text to be displayed or entered.
Set the AcceptsTab and AcceptsReturn properties to true to enable greater text
manipulation in a multiline TextBox control. It can also be used to accept
passwords and other sensitive information. You can use the PasswordChar
property to mask characters entered in the TextBox

You can limit the amount of text entered into a TextBox control by setting the
MaxLength property to a specific number of characters. Use the
CharacterCasing property to enable the user to type only uppercase, only
lowercase, or a combination of uppercase and lowercase characters into the
TextBox control.

Some Properties of TextBox


 Multiline : Gets or sets a value indicating whether this is a multiline
TextBox control.
 AcceptsReturn : Gets or sets a value indicating whether pressing ENTER
in a multiline TextBox control creates a new line of text in the control
 AcceptsTab : Gets or sets a value indicating whether pressing the TAB
key in a multiline text box control types a TAB character in the control
instead of moving the focus to the next control in the tab order
 PasswordChar : Gets or sets the character used to mask characters of
a password in a single-line TextBox control
 Text : Gets or sets the current text in the TextBox.
 SelectedText : Gets or sets a value indicating the currently selected text
in the control
 CharacterCasing : Gets or sets whether the TextBox control modifies
the case of characters as they are typed. The possible values are :Lower,
Normal or Upper
 ReadOnly : Gets or sets a value indicating whether text in the text box
is read-only

Some Methods of TextBox


 Clear() - Clears all text from the text box control.
 Copy() - Copies the current selection in the text box to the Clipboard.
 Cut() - Moves the current selection in the text box to the Clipboard
 Paste() - Replaces the current selection in the text box with the contents
of the Clipboard.
 SelectAll() - Selects all text in the text box.
 Undo() - Undoes the last edit operation in the text box
 Focus() - Sets input focus to the control
Important Event of TextBox
 TextChanged : Occurs when the Text property value changes.

Button Control
Buton control lets you generate a Click event; by handling the click event of a
button, you can make the user perform some action at the runtime. A Button
can be clicked by using the mouse, ENTER key, or SPACEBAR if the button
has focus.

Some Properties of Button

 Image : Gets or sets the image that is displayed on a button control.


 ImageAlign : Gets or sets the alignment of the image on the button
control
 Text : Gets or sets the text associated with this control.
 TextAlign : Gets or sets the alignment of the text on the button control.

Important event of Button


 Click : Occurs when the control is clicked.

You might also like